symfony - Symfony2 display related entity property in Twig template -
let's have product class , category class. each product has 1 category. on list of products (generated calling php app/console doctrine:generate:crud
), display category name each product. i've tried far doesn't work.
i'm using knppaginatorbundle (don't know if makes difference or not).
here's code inside controller:
// productcontroller.php public function indexaction(request $request) { $em = $this->getdoctrine()->getmanager(); $query = $em->createquery( 'select p mymainbundle:product p order p.name' ); $paginator = $this->get('knp_paginator'); $pagination = $paginator->paginate($query, $request->query->get('page', 1), 10); return $this->render('mymainbundle:product:index.html.twig', array( 'pagination' => $pagination, )); }
here's code inside template:
{# index.html.twig #} {% extends 'mymainbundle::layout.html.twig' %} {% block body -%} <table> <thead> <tr> <th>name</th> <th>category</th> </tr> </thead> <tbody> {% entity in pagination %} <tr> <td>{{ entity.name }}</td> <td>{{ entity.category }}</td> </tr> {% endfor %} </tbody> </table> {{ knp_pagination_render(pagination) }} {% endblock %}
i've added __tostring() method category class:
public function __tostring() { return $this->getname(); }
but following error:
method "category " object "my\mainbundle\entity\product" not exist in mymainbundle:product:index.html.twig @ line 16
i've tried adding left join p.category category
query, no avail.
i've tried replacing {{ entity.category }}
{{ entity.category.name }}
, in case get:
method "name " object "proxies__cg__\my\mainbundle\entity\category" not exist in mymainbundle:product:index.html.twig @ line 16
i've tried replacing {{ entity.category }}
{{ entity.getcategory }}
in case get:
method "getcategory " object "my\mainbundle\entity\product" not exist in mymainbundle:product:index.html.twig @ line 16
i've tried replacing {{ entity.category }}
{{ entity.getcategory() }}
in case get:
unexpected token "name" of value " " ("end of print statement" expected) in mymainbundle:product:index.html.twig @ line 16
how supposed display category name?
i noticed in both error messages:
method "category " object "my\mainbundle\entity\product" not exist in mymainbundle:product:index.html.twig @ line 16
and
method "name " object "proxies_cg_\my\mainbundle\entity\category" not exist in mymainbundle:product:index.html.twig @ line 16
you have space between method name , following "
.
this happened me before when typing code quickly: pressed key make twig }}
before typing space after property name, ended having non-breaking space between property , }}
, twig doesn't , takes part of property name.
check if don't have non-breaking space in code before }}
.
Comments
Post a Comment