Symfony动态修改表单

时间:2018-12-24 22:11:59

标签: symfony

我正在设置新的表格,其中包含两个字段,区域和城市。

,并希望在选择“区域”时进行设置,将提供受支持的城市列表作为“区域ID”。

我在“城市到区域”上配置ManyToOne。

我的表单生成器:

public function buildForm(FormBuilderInterface $builder, array $options): void
{
    $builder
        ->add('area', EntityType::class, [
            'class' => 'App:Area',
            'choice_label' => 'getName',
        ])
    $builder->get('area')->addEventListener(
        FormEvents::POST_SUBMIT,
        function (FormEvent $event) {
            $form = $event->getForm();
            $form->add('city', EntityType::class, [
                'class' => 'App\Entity\City',
                'choices' => $form->getData()->getCity()
            ]);
        }
    );

    $builder->addEventListener(
        FormEvents::POST_SET_DATA,
        function (FormEvent $event) {
            $form = $event->getForm();
            $data = $event->getData();
            $city = $data->getCity();

            if ($city) {
                $form->get('area')->setData($city->getCity);
                $form->add('city', EntityType::class, [
                    'class' => 'App\Entity\City',
                    'choices' => $city->getArea->getCity()
                ]);
            } else {
                $form->add('city', EntityType::class, [
                    'class' => '\App\Entity\City',
                    'choices' => $city->getArea->getCity()
                ]);
            }
        }
    );
}

城市实体:

 <?php

 namespace App\Entity;

 use Doctrine\ORM\Mapping as ORM;
/**
* @ORM\Entity
*/
class City
{
/**
 * @ORM\Id()
 * @ORM\GeneratedValue()
 * @ORM\Column(type="integer")
 */
private $id;
/**
 * @ORM\Column(type="string", length=50)
 */
private $name;
/**
 * @ORM\ManyToOne(targetEntity="App\Entity\Area")
 */
private $area;

public function getId(): ?int
{
    return $this->id;
}

public function getName(): ?string
{
    return $this->name;
}

public function setName(string $name): self
{
    $this->name = $name;

    return $this;
}

public function getArea(): ?Area
{
    return $this->area;
}

public function setArea(?Area $area): self
{
    $this->area = $area;

    return $this;
}
}

区域实体:

  <?php

  namespace App\Entity;

  use Doctrine\ORM\Mapping as ORM;

 /**
 * @ORM\Entity
  */
 class Area
 {
/**
 * @ORM\Id()
 * @ORM\GeneratedValue()
 * @ORM\Column(type="integer")
 */
private $id;

/**
 * @ORM\Column(type="string", length=100)
 */
private $name;

public function getId(): ?int
{
    return $this->id;
}

public function getName(): ?string
{
    return $this->name;
}

public function setName(string $name): self
{
    $this->name = $name;

    return $this;
}
}

我希望当我更改区域时,只会给我该区域的城市。

经过多次尝试。

现在我有错误:

在null上调用成员函数getCity()

我也尝试添加到FormBuilder

        ->add('city', EntityType::class, [
            'class' => 'App:City',
            'choice_label' => 'getName',
        ])

1 个答案:

答案 0 :(得分:0)

该字段的事件侦听器应为

$form = $event->getForm()->getParent();