Symfony2 form events and model transformers

后端 未结 3 1984
傲寒
傲寒 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:55

    Your listener looks (almost :) ) ok.

    Just use PRE_SUBMIT. In that case, $event->getData() will be the raw form data (an array) that is sent. $selectedFoo will potentailly contain "other".

    If it is the case, you will replace the "short" 'choice' field with a full one, by using formFactory in the listener.

    $builder->addEventListener(FormEvents::PRE_SUBMIT, function(FormEvent $event) {
        $data = $event->getData();
        if (empty($data['linkedFoo']) || $data['linkedFoo'] !== 'other') {
            return;
        }
    
        // now we know user choose "other"
        // so we'll change the "linkedFoo" field with a "fulllist"
    
    
        $event->getForm()->add('linkedFoo', 'choice', array(
            'choices' => $fullList, // $em->getRepository('Foo')->getFullList() ?
        ));
        $event->getForm()->get('linkedFoo')->getConfig()->addModelTransformer(new FooTransformer);
    });
    

    You asked so much questions I don't know where to start.

    Concerning dataTransformers: until you want to transform raw data into a different representation ("2013-01-01" -> new DateTime("2013-01-01")), then you don't need transformers.

提交回复
热议问题