Sruj
Sruj

Reputation: 1207

how to pass variable from twig path to the same controller?

In template i need to pass variable to controller when clicked link

{{ variable }}
<a href="{{ path('test',{ 'variable': 2}) }}">click</a>

. How to do this?

/**
 * @Route("/test", defaults={"variable" = 1}, name="test")
 * @Method("GET")
 * @Template()
 */
public function testAction($variable)
{
    return array('variable'=>$variable);
} 

You will say i need placeholder in @Route /test/{variable}, then how to first time visit url test?


edit: this is silly question. I had some cache problem while testing this issue. The answear is obvious.

Upvotes: 3

Views: 18822

Answers (2)

Alvin Bunk
Alvin Bunk

Reputation: 7764

I had to do something similar, and @Tomasz, your answer helped me a lot. I my case I needed two variables.

Using the above example as a reference:

 * @Route("/test/{variable}/{var2}",
 *    defaults={"variable" = 0, "var2" = 0},
 *    name="test")
 * @Method("GET")
 * @Template()
 */
public function testAction($variable, $var2)
{ 
    return array('variable'=>$variable, 'var2 => $var2);
}

Then in twig you can use:

<a href="{{ path('test', {'variable': 2, 'var2': 3}) }}">click</a>

which generates URL /test/2/3

In my case, I was using something more fancy, like an Entity:

<td><a href="{{ path('submitPetHasProgram',
    {'prog':stu.getTcProgram.getProgramId,
    'student':stu.getStuId}) }}">Select</a></td>

Hopefully this will help someone out in the future who is struggling for a solution to this type of problem.

Upvotes: 0

Tomasz Madeyski
Tomasz Madeyski

Reputation: 10890

You need to define your @Route annotation like you mention:

/**
 * @Route("/test/{variable}", defaults={"variable" = 0}, name="test")
 * @Method("GET")
 * @Template()
 */
public function testAction($variable)
{ 
    return array('variable'=>$variable);
} 

Thanks to defaults option you can access your route with or without variable:

  1. With:

    <a href="{{ path('test', {'variable': 2}) }}">click</a>
    

    This will generate url /test/2 and your $variable will equal 2

  2. Without:

     <a href="{{ path('test') }}">click</a>
    

    This will generate url /test and your $variable will equal 0 (a value set in defaults option)

Upvotes: 8

Related Questions