簡體   English   中英

提交后取消Symfony表單中的字段設置

[英]Unset fields in Symfony form after submit

在我的Symfony項目(2.7)中,我有一個實體Apartment ,具有很多屬性。 其中之一是Town Town是其他學說實體,它們具有City實體,而City具有State

在我的Apartment表格中,我有3個選擇。 對於TownCity 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); 
});

如果您需要在驗證過程之前將它們設置為NULLPOST_SUBMITSUBMIT

現在,在控制器內調用form->getData()將返回NULL值。

希望這可以幫助...

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM