Reputation: 2421
Let's say I have a Category entity, a Person entity, and these two are related by a Contract Entity.
In my view, I need to display a category with all its subcategories with the number of persons
For example : when the user is on the page to view "the category A", I would like he/she sees that :
Category A 10 persons
subcategory a.1 4 persons
subcategory a.2 6 persons
So in my show.html.twig, I would write :
{{ category.title }} {{ nb_persons }}
{% for child in children %}
{{ child.title }} //{{ child.getNbPersons() }}??, how to get the number of persons for each child ?
{% endfor %}
Here's my CategoryController.php
public function showAction($id_category)
{
$em=$this->getDoctrine()->getEntityManager();
$repo = $em->getRepository('MyBundle:Category');
$this->param['category']= $repo->find($id);
$this->param['nb_persons'] = $repo->getNbPersonsByCategory($id_category);
$this->param['children'] = $repo->children($this->param['category'], true, 'title');
return $this->render('MyBundle:Category:show.html.twig', $this->param);
}
But to display the number of persons for each subcategory(child) I need to use a method like child.getNbPersons(), but this would force me to use a repository function in my entity Category.php and this is a bad practice I think. What can I do ?
Upvotes: 1
Views: 92
Reputation: 20193
I tend to totally isolate model from everything else. That is, model is not aware controller, repositories etc.
Regarding your problem I would rather construct an appropriate object (well an array
) within controller and pass it to Twig
as it is and that array
should hold all the info needed precalculated. That way, if you have a lot of categories (and/or subcategories) you would have to exec database query only once, opposed to calling the repository from model method where each call would require a single query.
Hope this helps... ;)
Upvotes: 1