Symfony2 form events and model transformers

后端 未结 3 1995
傲寒
傲寒 2020-12-08 00:57

I\'m getting tied in knots trying to wrestle with Symfony2\'s form builders, events and transformers... hopefully somebody here is more experienced and can help out!

3条回答
  •  鱼传尺愫
    2020-12-08 01:37

    For anyone that is still looking for a better way to add/re-add a Model Transformer inside form events, I think that the best solution is the one from this post all credits go to @Toilal for this brilliant solution

    So if you implement the ModelTransformerExtension and define it as a service, and change some code, for example, from

    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder->addEventListener(
                FormEvents::PRE_SET_DATA,
                array($this, 'onPreSetData')
            );
        $builder->add(
                    $builder
                        ->create('customer', TextType::class, [
                            'required' => false,
                            'attr' => array('class' => 'form-control selectize-customer'),
                        ])
                        ->addModelTransformer(new CustomerToId($this->customerRepo))
                )
                ;
    }
    

    to something like:

    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder->addEventListener(
                    FormEvents::PRE_SET_DATA,
                    array($this, 'onPreSetData')
                );
        $builder->add('customer', TextType::class, [
                    'required' => false,
                    'attr' => array('class' => 'form-control selectize-customer'),
                    'model_transformer' => new CustomerToId($this->customerRepo),
                ]
            )
            ;
    }
    

    And now if we remove and re-add the desired field inside the eventlistener function, the Model Transformer for the field will not be lost.

    protected function onPreSetData(FormEvent $event)
    {
        $form = $event->getForm();
        $formFields = $form->all();
        foreach ($formFields as $key=>$value){
            $config = $form->get($key)->getConfig();
            $type = get_class($config->getType()->getInnerType());
            $options = $config->getOptions();
    
            //you can make changes to options/type for every form field here if you want 
    
            if ($key == 'customer'){
                $form->remove($key);
                $form->add($key, $type, $options);
            }
        }
    }
    

    Note that this is a simple example. I've used this solution to easily process a form to have multiple field states in different places.

提交回复
热议问题