Symfony 4多人关系允许添加表单生成器

时间:2019-07-04 07:51:42

标签: symfony

我在订阅实体和客户实体之间有多对多的关系。 我正在填写表格以向客户添加订阅。 通过这种形式,我可以选择一个已经存在的客户,但是如果不存在新客户,我希望能够创建一个新客户。

CustomerEntity:

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;
    }
}

SubscriptionEntity:

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;
    }
}

SubscriptionType(窗体):

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
        ]);
    }
}

因此,目前我可以为现有客户创建订阅,我想知道如何为不存在的客户创建订阅?

1 个答案:

答案 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
        ]);
    }
}