3

I was looking around for a solution, but I cannot find any in stackoverflow.

The following problem is that I want to pass an object to a twig template.

I have a class which extends the AbstractType of Symfony2 Core. Then I understood that I have to override the BuildView Method of my specific type to hand over the variable.

The buildView method looks like this:

/**
 *
 * @param FormView $view
 * @param FormInterface $form
 * @param array $options
 */
public function buildView(FormView $view, FormInterface $form, array $options)
{
    parent::buildView($view, $form, $options);
    $view->vars['test']='test';

}

When I try to access the variable in my twig file ({{test}}), it tells me variable test not found.

What do I misunderstand? Thanks for your help AS

AugustusS
  • 43
  • 6

2 Answers2

0

Without seeing the whole code, I suspect that you are adding the view vars to a child view when there is a parent view present.

$view->parent->vars['test'] = 'test';

Hopefully fixes your issue.

MichaelHindley
  • 485
  • 3
  • 7
  • I tried that, but then I get: An exception has been thrown during the rendering of a template ("Notice: Undefined index: cache_key") in src/AppBundle/Resources/views. Interestingly, I do not get this bug report when I do $view->vars['test]='test'; – AugustusS Feb 07 '15 at 17:57
  • Hm ok, try removing everything in your buildView except for the parent:: call, and then under it add this: $view->vars = array_replace($view->vars, array( 'test' => 'test' )); The cache_key key is part of BaseType class which extends the AbstractType class, are you using it anywhere? – MichaelHindley Feb 07 '15 at 18:21
  • I am not using the BaseType anywhere else. Changing this using your advice is leading me to the same problem again that he cannot find the variable test. If I add this line "$view->vars['test']='test';" to the Abstract Class method buildView then he can find the variable test. – AugustusS Feb 07 '15 at 18:38
  • Have you tried settings the $view->vars['test'] = 'test' before calling the parent::buildView? Which version of Symfony are you using? – MichaelHindley Feb 08 '15 at 07:22
  • using the most current version of Symfony – AugustusS Feb 08 '15 at 08:06
  • Are you using any REST library or any custom onKernelResponse eventlisteners that could change something with the view vars? I am at a loss otherwise, sorry :/ – MichaelHindley Feb 09 '15 at 07:04
0

You are attaching the new var 'test' to your form, so to access it you have to make it through the form :

{{ formName.vars.test }}

Hope it helps !

Djagu
  • 163
  • 1
  • 12