Symfony:如果未在Form中提交,则将字段设置为null

时间:2017-08-08 09:39:22

标签: php forms symfony

对于此示例,我们假设我有Vehicle个实体,其中包含以下值:

  • Type:自行车,摩托车,汽车
  • Fuelinteger

我通过动态表单创建一个新的Vehicle对象。请注意,该字段"燃料"如果字段type设置为" Bicycle"。

,则不会显示

我可以成功创建此表单,这要归功于Symfony文档作为一些javascript:

<?php


$formModifier = function (FormInterface $form, $fields = null, array $options) {
    foreach ($fields as $field_id => $field_value) {
        if ($field_id == 'type') {
            if ($field_value && $field_value == 'bicycle') {
                $form->remove('gas');
            } elseif ($field_value && $field_value == 'motorbike') {
                $form->add('gas');
            } elseif ($field_value && $field_value == 'car') {
                $form->add('gas');
            }
        }
    }
};

$builder->addEventListener(
    FormEvents::PRE_SUBMIT,
    function (FormEvent $event) use ($formModifier, $options) {
        $formModifier($event->getForm(), $event->getData(), $options);
    }
);
$builder->addEventListener(
    FormEvents::PRE_SET_DATA,
    function (FormEvent $event) use ($formModifier, $options) {
        $vehicule = $event->getData();

        $formModifier($event->getForm(), array(
            'type' => $vehicule->getType(),
        ), $options);
    }
);

$builder->add('type', ChoiceType::class, array(
    'choices' => array(
        'Bicycle'   => 'Bicycle',
        'Motorbike' => 'Motorbike',
        'Car'       => 'Car',
    ),
));

然后使用Doctrine保存数据。

但是,如果数据库中的实体已经定义了气体,则在编辑此表单时会出现问题。

例如:

  1. 数据库中的实体是Motorbike gas = 10
  2. 我想编辑表单。该页面显示了Type和Gas两个字段。 3.然后我选择&#34; Bicycle&#34;。该领域&#34; Gas&#34;消失。
  3. 我提交表格。属性Type已更新,现在值为Bicycle但不是属于Gas的属性10
  4. 在这种情况下,如何将gas属性设置为零?

1 个答案:

答案 0 :(得分:0)

添加SUBMIT表单事件:

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

    if($data['type'] == 'Bicycle'){
        $data['gas'] = 0; //Note that in your entity, this field is named 'fuel'...
    }
    $event->setData($data); 
});