Symfony,如何使用表单事件来验证动态客户端表单

Symfony, how to use form event to validate dynamic client-side form

我正在使用带有 ajax 的 select2 插件在我的表单上有一个动态字段,但是当我提交它时 return 我出错了 "This value is not valid",这是正常的,因为我在创建时的 choices 选项中使用 ChoiceType 和空 array()。根据 symfony 文档的 this 部分,表单事件是我的救星,所以尝试使用它但它看起来像我的代码有问题并且无法真正看到什么。

所以我的问题是:

如何将选择可能性传递给字段,以使表单有效。

我的表单类型

class ArticleType extends AbstractType
{
    /**
     * {@inheritdoc}
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            //My other field

        //My functions to add the field with the possible choices
        $formModifier = function (FormInterface $form, $imageValue) use ($options) {
            if ($imageValue !== null) {
                $listImages = $this->getChoiceValue($imageValue, $options);

                if (!$listImages) {
                    $form->get('image')->addError(new FormError(
                    'Nous n\'avons pas pu trouver l\'image, veuiller choisir une autre'
                    ));
                }
            } else {
                $listImages = array();
            }

            //die(var_dump($listImages)); //Array of Image

            $form->add('image', ChoiceType::class, array(
                'attr' => array(
                    'id' => 'image'),
                'expanded' => false,
                'multiple' => false,
                'choices' => $listImages));
        };

        $formModifierSubmit = function (FormInterface $form, $imageValue) use ($options) {
            if ($imageValue !== null) {
                $listImages = $this->getChoiceValue($imageValue, $options);

                if (!$listImages) {
                    $form->get('image')->addError(new FormError(
                        'Nous n\'avons pas pu trouver l\'image, veuiller choisir une autre'
                    ));
                }
            } else {
                $form->get('image')->addError(new FormError(
                    'Veuillez choisir une image s.v.p.'
                ));
            }

            //die(var_dump($listImages)); //Array of Image object

            $config = $form->get('image')->getConfig();
            $opts = $config->getOptions();
            $chcs = array('choices' => $listImages);
            //die(var_dump($chcs)); //output an array with a 'choices' keys with array value
            array_replace($opts, $chcs); //not work
            //array_merge($opts, $chcs); //not work
            //die(var_dump($opts)); //replacements/merge are not made
        };

        $builder->addEventListener(
            FormEvents::PRE_SET_DATA,
            function (FormEvent $event) use ($formModifier) {
                // this would be the entity Article
                $data = $event->getData();

                $formModifier($event->getForm(), $data->getImage());
            }
        );

        //$builder->get('image')->addEventListener( //give error cause the field image don't exist
        $builder->addEventListener(
            FormEvents::PRE_SUBMIT,
            function (FormEvent $event) use ($formModifierSubmit) {
                $imageVal = $event->getData();
                //die(var_dump($imageVal)); //return all the submitted data field in an array
                //But when change this event to Submit it return the Article model populated by the submitted data, EXCEPT the image field which have null as value

                $formModifierSubmit($event->getForm(), $imageVal['image']);
            }
        );
    }

    public function getChoiceValue($imageValue, $options)
    {
        $listImages = $options['em']->getRepository('AlmotivAppBundle:Image')->findBy(array(
            'id' => $imageValue
        ));

        return $listImages; //array of Image object
    }
    [...]
}

参考资料

我的 image 字段不像文档示例那样依赖于任何其他字段,因此我需要在 PRE_SUBMIT 事件上填充 choices 选项以提供可能的选择。

而且 image 在我的 Article 实体中有一个 ManyToOne 关系

class Article implements HighlightableModelInterface
{
    //some properties
    /**
     * @ORM\ManyToOne(targetEntity="Image\Entity\Path", cascade={"persist"})
     * @Assert\Valid()
     */
    private $image;
}

如果我的方法不对请告诉我,因为我现在完全不懂,我尝试了很多东西,比如

还有更多(记不清了)。

而且我正在使用框架的 v3.1 和 select2 插件的 v4.0.3,如果需要更多信息,请询问并感谢阅读和尝试帮助。

编辑

添加一些信息更清楚

你把事情搞得太复杂了。在您的文档示例中,他们为已经存在的表单字段('sport')添加了 eventListener,而您只是将其添加到后来添加的不存在的字段(您的 'image' 字段和 'position' 字段来自文档示例)。

你应该使用 EntityType and if you need (which I'm not if sure you are) filter your images using query_builder option, for validation add constraints (example with controller).

class ArticleType extends AbstractType {
/**
 * {@inheritdoc}
 */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {

         // $builder
         // My other field
         $imageFieldFunction = $this->getImageFieldFunction();

         $builder->addEventListener(FormEvents::PRE_SET_DATA, $imageFieldFunction);
         $builder->addEventListener(FormEvents::PRE_SUBMIT, $imageFieldFunction);

    }
    private function getImageFieldFunction()
    {
         return function(FormEvent $event) {
             $form = $event->getForm();
             $data = $event->getData();
             //when your data_class is Article 
             $image = $data->getImage();//depending on your Article class
             /*if you are using data_class => null
             $image = $data['image'];
              */
             $imageId = $image ? $image->getId() : 0;

             $builder->add('image', EntityType::class , array(
            'class' => 'AlmotivAppBundle:Image',
             'attr' => array(
                'id' => 'image'
             ) ,
             'expanded' => false,
             'multiple' => false,
             'constraints' => new NotBlank(),
             'query_builder' => function (EntityRepository $er) use ($imageId) {
                  return $er->createQueryBuilder('i')
                            ->where('i.id = :image_id')
                            ->setParameter('image_id', $imageId);
             }

         ));
         }
    }
}