我在订阅实体和客户实体之间有多对多的关系。 我正在填写表格以向客户添加订阅。 通过这种形式,我可以选择一个已经存在的客户,但是如果不存在新客户,我希望能够创建一个新客户。
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
]);
}
}
因此,目前我可以为现有客户创建订阅,我想知道如何为不存在的客户创建订阅?
答案 0 :(得分:0)
有关完整的实现,请参阅此官方文档:https://symfony.com/doc/current/reference/forms/types/collection.html 您必须使用CollectionType来包含您案例中的客户集合。然后,在您的树枝中,编写一些jquery以动态添加新客户。 像这样:
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
]);
}
}