Access variable from FormType in branch type templates

I created my own type of form, for example:

class PositioningFlashType extends AbstractType { public function setDefaultOptions(OptionsResolverInterface $resolver) { $resolver->setDefaults(array( 'game' => new Game() )); } public function getParent() { return 'form'; } /** * Returns the name of this type. * * @return string The name of this type */ public function getName() { return 'positioning_flash'; } } 

And in another form ( GameType ) I use it as follows:

 $builder ->add('flash', new PositioningFlashType(), array( 'mapped' => false, 'game' => $options['game'] )) 

And inside the controller I want to create the whole form:

 private function createEditForm(Game $entity) { $form = $this->createForm(new GameType(), $entity, array( 'action' => $this->generateUrl('game_update', array('id' => $entity->getId())), 'method' => 'PUT', 'edit' => true, 'game' => $entity )); $form->add('submit', 'submit', array('label' => 'Speichern')); return $form; } 

Basically, all I want to do is pass a Game instance to PositioningFlashType and inside the template. I want to access this instance of Game as follows:

 value="{{ asset('data/swf/backendtool.swf') }}?game={{ game.id }} 

But symfony throws an error saying that the Game variable is not defined.

What is the correct way to pass a variable from a controller to a nested FormType?

+8
symfony twig symfony-forms
source share
1 answer

You can add custom view variables by wrapping buildView() .

 /* ... */ use Symfony\Component\Form\FormView; use Symfony\Component\Form\FormInterface; /* ... */ class PositioningFlashType extends AbstractType { /* ... */ public function buildView(FormView $view, FormInterface $form, array $options) { parent::buildView($view, $form, $options); $view->vars = array_merge($view->vars, array( 'game' => $options['game'] )); } /* ... */ } 

You now have a game under form.vars . Just redefine your custom form widget to do whatever you need with it.

 {% block positioning_flash_widget %} {% spaceless %} {# ... #} <input value="{{ form.vars.game.id }}" /> {% endspaceless %} {% endblock %} 
+16
source share

All Articles