在 Symfony 3 中为集合的每个项目指定不同的验证组? [英] Specify different validation groups for each item of a collection in Symfony 3?

查看:30
本文介绍了在 Symfony 3 中为集合的每个项目指定不同的验证组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个项目实体,里面有很多图片,每个图片都有标题,imageFile 属性

I have a project entity which has many images, every image has title, imageFile attributes

我希望用户能够在项目表单中添加、更新和删除图像.

I want the user to be able to add, update and delete images from the project form.

问题是 projectImage 实体验证组在新建时应该与编辑时不同.

The problem is that the projectImage entity validation groups when it is new should be different from when it is being edited.

这是代码

项目类型

class ProjectType extends AbstractType
{

    /**
     * @param FormBuilderInterface $builder
     * @param array $options
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->addEventSubscriber(new \ControlPanelBundle\Form\EventListener\CityFieldSubscriber())
            ->addEventSubscriber(new \ControlPanelBundle\Form\EventListener\CountryFieldSubscriber());

        $builder
            ->add('title')
            ->add('description')
            ->add('area')
            ->add('startDate')
            ->add('deliveryDate')
            ->add('phases')
            ->add('partners', EntityType::class, [
                'class'         => 'AppBundle:Partner',
                'multiple'      => true,
                'query_builder' => function (EntityRepository $er) {
                    return $er->createQueryBuilder('p')
                        ->orderBy('p.title', 'ASC');
                }
            ])
            ->add('projectImages', CollectionType::class, [
                'entry_type'     => ProjectImageType::class,
                'allow_add'      => true,
                'allow_delete'   => true,
                'delete_empty'   => true,
                'by_reference'   => false,
                'error_bubbling' => false
        ]);
    }

    /**
     * @param OptionsResolver $resolver
     */
    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => 'AppBundle\Entity\Project'
        ));
    }

    /**
     * @return string
     */
    public function getName()
    {
        return 'project';
    }
}

ProjectImageType

class ProjectImageType extends AbstractType
{

    /**
     * @param FormBuilderInterface $builder
     * @param array $options
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('id', HiddenType::class)
            ->add('title', TextType::class)
            ->add('type', ChoiceType::class, ['choices' => array_flip(\AppBundle\Entity\ProjectImage::getTypeChoices())])
            ->add('imageFile', FileType::class);
    }

    /**
     * @param OptionsResolver $resolver
     */
    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults([
            'data_class'        => 'AppBundle\Entity\ProjectImage',
            'validation_groups' => function(\Symfony\Component\Form\FormInterface $form) {
                $validationGroups = ['Default'];

                if ($form->getData() === null || null === $form->getData()->getId()) {
                    $validationGroups[] = "newImage";
                }

                return $validationGroups;
            }
        ]);
    }

    public function getName()
    {
        return 'project_image';
    }
}

正如您在 ProjectImageType 中看到的,如果图像是新图像或者用户想要添加新图像,我将添加一个验证组newImage",在这种情况下,只需要图像文件,而不应该需要如果用户只想更新图片的标题.

as you can see in the ProjectImageType I'm adding a validation group "newImage" if the image is new or if the user want to add new image, in this case only the image file should be required and should not be required if the user want to just update the title of the image.

问题是我在 ProjectImageType 中添加的验证组newImage"总是被忽略.

the problem is that validation group "newImage" which I'm adding in the ProjectImageType always ignored.

我尝试了此处提供的解决方案 在 Symfony 2 中为集合的每个项目指定不同的验证组?但问题是从 symfony 3 中删除了 cascade_validation 选项

I tried the solution provided here Specify different validation groups for each item of a collection in Symfony 2? but the problem is that the cascade_validation option removed from symfony 3

这里的问题是如何根据彼此不同的验证组以及与父表单类型验证组不同的验证组来验证每个集合类型实体?

the question here is how can can validate every collection type entity against different validation groups from each other and also different from the parent form type validation groups?

推荐答案

我通过在项目实体中添加回调验证解决了这个问题,没有使用验证组,如下所示:

I resolved the problem without using validation groups by adding a callback validation in the project entity as following:

ProjectImage 实体

/**
 * assert that image not blank only if new object
 *
 * @Assert\Callback
 */
public function validateImage(ExecutionContextInterface $context) {
    if (null === $this->id && null === $this->getImageFile()) {
        $context->buildViolation('Image is required')
                ->atPath('imageFile')
                ->addViolation();
    }
}

这篇关于在 Symfony 3 中为集合的每个项目指定不同的验证组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆