如何使Symfony2表单可选字段在保存时不为null

时间:2016-11-30 11:58:28

标签: php symfony doctrine-orm

我有一个可选的图像字段。上传图像时,它会将文件名保存在数据库中(通过学说使用事件)。

问题是当您编辑已上传的表单并且不添加图像时,它会使图像字段为空。

如果没有上传图像,有没有办法检查/删除字段值设置为空?

实体,表格代码如下:

class ProductType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder->add('image', FileType::class, [
            'required' => !$options['update'],
        ]);

        $builder->addEventListener(FormEvents::PRE_SET_DATA, function (FormEvent $event) {
            $form = $event->getForm();
            $product = $event->getData();

            if (null == $form->get('image')->getData()) {
                // $form->remove('image');
            }
        });
    }

    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => 'AppBundle\Entity\Product'
        ));
    }

    public function getBlockPrefix()
    {
        return 'appbundle_product';
    }

    public function setDefaultOptions(OptionsResolverInterface $resolver)
    {
        $resolver->setRequired([
            'update',
        ]);
    }
}

表格

$editForm = $this->createForm(
    'AppBundle\Form\ProductType', 
    $product, 
    [
        'update' => true
    ]
);

//在控制器中

max

2 个答案:

答案 0 :(得分:2)

你需要事件PRE_SUBMIT,试试这个:

public function buildForm(FormBuilderInterface $builder, array $options)
{
    $builder->add('image', FileType::class, [
        'required' => !$options['update'],
    ]);

    $builder->addEventListener(FormEvents::PRE_SUBMIT, function (FormEvent $event) {
        $form = $event->getForm();
        $product = $event->getData();

        if(empty($product['image'])){
            //No new image for existing field was given. Make field disabled so doctrine will not update with empty
            $config = $event->getForm()->get('image')->getConfig();
            $options = $config->getOptions();
            $event->getForm()->add(
                'image',
                $config->getType()->getName(),
                array_replace(
                    $options,
                    ['disabled' => true]
                )
            );
        }
    });
}

答案 1 :(得分:0)

Symfony Form有submit()方法,它接受两个参数,$ submittedData和$ clearMissing

/**
 * Submits data to the form, transforms and validates it.
 *
 * @param null|string|array $submittedData The submitted data
 * @param bool              $clearMissing  Whether to set fields to NULL
 *                                         when they are missing in the
 *                                         submitted data.
 *
 * @return FormInterface The form instance
 *
 * @throws Exception\AlreadySubmittedException If the form has already been submitted.
 */
public function submit($submittedData, $clearMissing = true);

$ clearMissing参数默认设置为true。

如果您在控制器中执行此操作:$form->submit($submittedData, false);,则您的图片不会设置为空。

https://symfony.com/doc/current/form/direct_submit.html#calling-form-submit-manually

类似的问题:Symfony2 - How to stop Form->handleRequest from nulling fields that don't exist in post data