1

I've just started using Symfony. I want to echo the $bookid when I call a URL like book/5 , but I stuck somewhere.

Here's my DefaultController.php file

namespace AppBundle\Controller; use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route; use Symfony\Bundle\FrameworkBundle\Controller\Controller; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; class DefaultController extends Controller { /** * @Route("/book/{id}", name="book") */ public function indexAction() { return $this->render('default/index2.html.php'); } } 

file: /Myproject/app/Resources/views/default/index2.html.php

<?php echo $id; ?> 

When I call the book/6 , I get a blank page. What's missing? Do I need to change somewhere else, too?

2 Answers 2

4

You should declare that variable in your action and pass it to your view.

namespace AppBundle\Controller; use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route; use Symfony\Bundle\FrameworkBundle\Controller\Controller; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; class DefaultController extends Controller { /** * @Route("/book/{id}", name="book") */ public function indexAction($id) { return $this->render('default/index2.html.php', array( 'id' => $id )); } } 

Whenever you have a parameter defined in your URL, you also need to "declare" it in your action function, so symfony maps it. Then, if you want to use it in your view, you have to pass it along.

Sign up to request clarification or add additional context in comments.

5 Comments

Thanks, but I still can't see the id echoed if I use .php instead of .twig. Do I need to add something to my routing.yml file, too?
Can you debug it a bit, just to make sure? Remove echo $id; from the template and just put echo 'test'; to make sure you render the right template?
I made a change in the app/config/config.yml to be able to work with .php files rather then twig, now I'm getting an error : "The template "default/index2.html.php" does not exist."
I changed 'default/index2.html.php' to '::default/index2.html.php' and it works. Not sure it's correct use.
Great! It is the correct syntax, check symfony.com/doc/current/book/… for more info.
2

If you are just starting with Symfony, I strongly recommend reading the Symfony Book and Cookbook. They are full of examples and relatively easy to understand, even for a newbie.

Other than that, the answer from smottt is correct. You add {id} in your route definition and receive it as parameter in your controller action.

Symfony book: Routing

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.