Reputation: 13
I have a problem with symfony 2 ( I'm pretty new with this framework and I would like to learn how to use correctly so I hope you can help me).
My problem is the following:
I want to show a product in a template and I need to pass some parameters like name, description and price about him:
public function showAction($id)
{
$product = $this->getDoctrine()->getRepository('AcmeReadBundle:Product')->find($id);
if(!$product)
{
throw $this->createNotFoundException('error: not found');
}
$content = $this->renderView('AcmeReadBundle:Show:index.html.twig',$product);
return new Response($content);
}
If I do this I have this error:
Catchable Fatal Error: Argument 2 passed to Symfony\Bundle\FrameworkBundle\Controller\Controller::renderView() must be of the type array, object given
How can I fix this?
Upvotes: 1
Views: 9056
Reputation: 2006
If template AcmeReadBundle:Show:index.html.twig is made for Product, it is wrong to put another "product" prefix in front of expressions, like so:
{{ product.title }}
{{ product.price }}
It is right to look it like this:
{{ title }}
{{ price }}
in template. So wrapping is a bad option. Best option is to use get_object_vars()
, it automatically converts object to an array:
return $this->render('AcmeReadBundle:Show:index.html.twig', get_object_vars($product));
This way you can use this template calling it from another template (because it doesn't contain "product"-prefix before every expression), when iterating thru Products
collection for example, because your Products
collection would contain collection of Products
, not collection of Arrays of 1 object which is Product
.
Upvotes: 0
Reputation: 410
you need to put:
$return $this->renderView('AcmeReadBundle:Show:index.html.twig',array('product' => $product));
you shoud pass parameters like array
Upvotes: 0
Reputation: 1192
you did quite alright, except you should pass parameters to templates in an array and it is better to return rendered template directly!
public function showAction($id)
{
$product = $this->getDoctrine()->getRepository('AcmeReadBundle:Product')->find($id);
if(!$product)
{
throw $this->createNotFoundException('error: not found');
}
return $this->render('AcmeReadBundle:Show:index.html.twig', array('product'=> $product));
}
Upvotes: 6