在我的Symfony项目(2.7)我有一个实体Apartment
,有很多属性。其中一个是Town
。Town
是另一个学说实体,它们有一个City
实体,City
有一个State
。
在我的Apartment
表单中,我有3个选择。对于Town
, City
和State
。但是当我想保存时,我只需要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"
));
...
可以不设置我不想保存的实体的额外字段Apartment?
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".
一旦提交,表单数据不能被更改。但是,您可以在提交最终化之前附加一个事件侦听器来执行此操作:
# 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
-ed,请将POST_SUBMIT
替换为SUBMIT
。
现在,在控制器中调用form->getData()
将返回NULL
值。