symfony - Symfony 4 manytoone 关系允许在表单构建器中添加
问题描述
我在订阅实体和客户实体之间建立了多方关系。我正在制作表格以向客户添加订阅。在这种形式中,我可以选择一个已经存在的客户,但如果它不存在,我希望能够创建一个新客户。
客户实体:
class Customer implements \JsonSerializable
{
/**
* @var int
*
* @ORM\Id
* @ORM\GeneratedValue
* @ORM\Column(type="integer")
*/
private $id;
/**
* @var string
*
* * @ORM\Column(type="string", length=180, unique=true)
*/
private $name;
public function getId(): ?int
{
return $this->id;
}
public function setName(string $name): void
{
$this->name = $name;
}
public function getName(): ?string
{
return $this->name;
}
/**
* {@inheritdoc}
*/
public function jsonSerialize(): string
{
return $this->name;
}
public function __toString(): string
{
return $this->name;
}
}
订阅实体:
class Subscription
{
/**
* @ORM\Id()
* @ORM\GeneratedValue()
* @ORM\Column(type="integer")
*/
private $id;
/**
* @ORM\ManyToOne(targetEntity="App\Entity\Customer")
* @ORM\JoinColumn(nullable=false)
*/
private $customerName;
public function getId(): ?int
{
return $this->id;
}
/**
* @return CustomerName
*/
public function getCustomerName()
{
return $this->customerName;
}
public function setCustomerName($customerName): self
{
$this->customerName = $customerName;
return $this;
}
public function __toString()
{
return $this->customerName;
}
}
订阅类型(表单):
class SubscriptionType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('customerName', null, array(
'required' => true,
));
}
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults([
'data_class' => TicketSubscription::class,
'customerName' => null
]);
}
}
所以目前我可以为现有客户创建订阅,我想知道如何为不存在的客户创建订阅?
解决方案
Refers to this official doc for complete implementation: https://symfony.com/doc/current/reference/forms/types/collection.html You have to use CollectionType to contains the collection of the customer in your case. Then, in your twig, write some jquery to dynamically add a new customer. Something like:
class SubscriptionType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('customers', CollectionType::class, array(
'entry_type' => CustomerType::class,
'entry_options' => [
'allow_add' => true,
'prototype' => true
]
));
}
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults([
'data_class' => TicketSubscription::class,
'customerName' => null
]);
}
}
推荐阅读
- java - 更新到 tzdata2019b 失败 - tzupdater 版本 2.2.0-b01
- python - 多处理稍后添加参数
- asp.net-mvc - 在 Visual Studio 2017 中编译时键入脚本编译器显示错误
- r-markdown - 使用带有 cbind 或其他方法的 kable 函数来选择变量
- ios - 依赖注入快速查看控制器的建议
- google-earth-engine - 如何估计焦点和
- docker - k8s securityContext.runAsUser vs Dockerfile USER 指令
- wordpress - 如何从评论/评论中获取 woocommerce 用户帐单地址
- javascript - Javascript循环并添加对象
- angular - 将角度 7 更新为 8 后缺少导入路径