Reputation: 31548
I have the class categroies
and class Products
.
In my repository i have function
getProducts($categoryid,$location)
I need to loop in twig template like this
{% for category in categories %}
--{{ category.name }}--
{% for product in getProducts(category.id,location) %}
--{{ product.name }}--
{% endfor %}
{% endfor %}
or is there any better way for that
Upvotes: 12
Views: 18282
Reputation: 1630
It's a pretty old question, but I'm missing a really simple solution like this one.
It is possible to pass the repo object to twig and call the repo public methods from twig like so:
In your controller
$oCatRepo = $this->getDoctrine()->getManager()->getRepository('AppBundle:Categories');
....
return $this->render('product_list.html.twig', array('oCatRepo' => $oCatRepo));
And then in your twig template :
{{ oCatRepo.getProducts(category.id, location) }}
Im saying it's possible, many would argue that templates should only display data and let controllers gather the data. I personally don't mind letting my templates getting their data themselves.
Upvotes: 7
Reputation: 3085
The solution is the other way around as how this is done right now. The Category entity should have a one-to-many relation. Take a look at http://symfony.com/doc/2.0/book/doctrine.html#entity-relationships-associations
The category Entity should then have an EntityCollection attribute called 'products'. In your template you then can solve this in the following way:
{% for category in categories %}
--{{ category.name }}--
{% for product in category.products %}
--{{ product.name }}--
{% endfor %}
{% endfor %}
Upvotes: 1
Reputation: 48865
I suspect that all you really need is a left join using a WITH expression. Something like:
class CategoryManager
{
public function loadCategoriesProductsForLocation($location)
{
$qb = $this->em->->createQueryBuilder();
$qb->addSelect('category');
$qb->addSelect('product');
$qb->from('MyBundleBundle:Category','category');
$qb->leftJoin('category.products','product',
Expr\Join::WITH, $qb->expr()->eq('product.location', $location));
That will give you all the categories with their respective products for a given location.
Upvotes: 1
Reputation: 131881
You shouldn't. Thats business logic, that should not appear in templates. One solution is to create a new action within a controller and in your template call
{% render '@MyBundle:Product:list' with {category: category.id} %}
Upvotes: 20