gpt4 book ai didi

php - 提交后取消设置 Symfony 表单中的字段

转载 作者:行者123 更新时间:2023-12-02 09:37:26 25 4
gpt4 key购买 nike

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

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

...
$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".

最佳答案

一旦提交,表单数据就无法更改。但是您可以在提交完成之前附加一个事件监听器来执行此操作:

# 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

现在,在 Controller 中调用 form->getData() 将返回 NULL 值。

希望这有帮助...

关于php - 提交后取消设置 Symfony 表单中的字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31812959/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com