hz4web
hz4web

Reputation: 29

set variables to twig when redirect link?

i want to set a variable to twig when redirect link like when use the render methods :

return $this->render('socialBundle::index.html.twig',array(
                    'id' => $id
                ));

it will set the Id variable to twig : {{ id }}

return $this->redirect($this->generateUrl("tuto_animaux_voir", array(
                    'id' => $id
                )));

it will set the Id variable to the link : xxxxx.com/Id , i want that it render this variable to twig when redirect ...

sorry for this bad concept and language because i'm not england , and this is my first question in stackoverflow ,

wait for a reponse , thanks

Upvotes: 1

Views: 4092

Answers (3)

rck6982
rck6982

Reputation: 239

I don't quite understand what you want to do, if you want to put a link in a twig template or just redirect from a controller according a condition. if you can give more details of what you want to do I think I can help you.

UPDATE (solution)

You could use "Forwarding to Another Controller" instead of using "Redirect" and from there to send the variables to the twig template

Upvotes: 1

Mateusz Sip
Mateusz Sip

Reputation: 1280

In you case 'tuto_animaux_voir' is a route associated to controller action. Given id will be available as action parameter, so you can pass it like this:

public function fooAction($id)
{
    return $this->render(
        'socialBundle::foo.html.twig',
        ['id' => $id]
    )
}

You can also fetch data from database and pass them to the view.

If that's not what to you want to achieve, tell us why you want to use redirect, and what these two actions should do.

Edit: If I understood your comment correctly, you want to implement flash messages, which are already available in symfony.

Example in docs is simple and self-explanatory.

Upvotes: 0

Isabek Tashiev
Isabek Tashiev

Reputation: 1044

Based on your last comment, I came to the following conclusion.

Assume that you have index action, with route tuto_animaux_voir. And route has one parameter id. It takes id as parameter and fetches alert from the database(we have alerts on the database). Also we have entity Alert with fields id(default), title.

...

public function indexAction($id){
  $alert = $this->getDoctrine()->getEntityManager("AppBundle:Alert")->find($id);

  return $this->render("AppBundle:Post:index.html.twig", array(
     'alert' => $alert
  ));
}

In your template index.html.twig you can show your alert.

...
 {{ alert.title }}
...

If you want to redirect to the index action in the twig.

<a href="{{ path("tuto_animaux_voir", { 'id': alert_id })}}">Alert Title<a>

Also if you want render this action as partial.

{{ render(controller('AppBundle:Alert:index',{'id': alert_id})) }}

I think my answer would be helpful for you.

Upvotes: 0

Related Questions