【问题标题】:Symfony : set fields as null if not submitted in FormSymfony:如果未在表单中提交,则将字段设置为空
【发布时间】:2017-08-08 09:39:21
【问题描述】:

对于这个例子,假设我有一个 Vehicle 实体,它可以具有以下值:

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

我通过动态表单创建了一个新的 Vehicle 对象。请注意,如果字段type 设置为“自行车”,则不会显示“燃料”字段。

感谢 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. 数据库中的实体是Motorbikegas = 10
  2. 我想编辑表单。该页面向我显示了 Type 和 Gas 两个字段。 3. 然后我选择“自行车”。 “Gas”字段消失。
  3. 我提交了表格。属性 Type 已更新,现在具有值 Bicycle但不是属性Gas,它保留在10

在这种情况下如何将gas属性设置为零?

【问题讨论】:

  • 您已经编辑了您的问题,但没有说明我的回答...有帮助吗?

标签: php forms symfony


【解决方案1】:

添加提交表单事件:

$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); 
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-02-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-06
    • 1970-01-01
    相关资源
    最近更新 更多