提交后,在Symfony表单中取消设置字段

时间:2015-08-04 15:11:13

标签: php forms symfony doctrine-orm

在我的Symfony项目(2.7)中,我有一个实体Apartment,有很多属性。其中之一是TownTown是其他学说实体,他们拥有City个实体,City拥有State

在我的Apartment表单中,我有3个选择。对于TownCityState。但是当我想保存时,我只想要Town

...
$builder->add('town', 'entity', array(
    'label' => 'Town',
    'choices' => $towns,
    'class' => "AppBundle\Entity\Town"
));
$builder->add('city', 'entity', array(
    'label' => 'City',
    'choices' => $cities,
    'class' => "AppBundle\Entity\City"
));
$builder->add('state', 'entity', array(
    'label' => 'States',
    'choices' => $states,
    'class' => "AppBundle\Entity\State"
));
...

有可能取消我不想保存实体公寓的额外字段吗?

if ($request->getMethod() == 'POST') {
    $form->handleRequest($request);

    if ($form->isValid()) {

        //I want to unset State and City entities. 
        $apartment = $form->getData();
        ...
    }

我有这个错误:

Neither the property "state" nor one of the methods "addState()"/"removeState()", "setState()", "state()", "__set()" or "__call()" exist and have public access in class "AppBundle\Entity\Apartment".

1 个答案:

答案 0 :(得分:6)

提交后,表单数据不能更改。但是您可以在提交最终确定之前附加一个事件监听器来执行此操作:

# Don't forget these
use Symfony\Component\Form\FormEvents;
use Symfony\Component\Form\FormEvent;

# ...

$builder->add('city', 'entity', array(
    'label' => 'City',
    'choices' => $cities,
    'class' => "AppBundle\Entity\City",
    'mapped' => FALSE // <-- This is important
));

$builder->addEventListener(FormEvents::POST_SUBMIT, function(FormEvent $event){
    $data = $event->getData();

    $data['city'] = NULL;
    $data['state'] = NULL;
    # We need this because of PHP's copy on write mechanism.
    $event->setData($data); 
});

如果您需要在验证过程之前NULL编辑这些内容,请将POST_SUBMIT换成SUBMIT

现在,在控制器中调用form->getData()将返回NULL个值。

希望这会有所帮助......