1
votes

In a Symfony2.1 project, how to call custom entity functions inside template? To elaborate, think the following scenario; there are two entities with Many-To-Many relation: User and Category.

Doctrine2 have generated such methods:

$user->getCategories();
$category->getUsers();

Therefore, I can use these in twig such as:

{% for category in categories %}
   <h2>{{ category.name }}</h2>
   {% for user in category.users %}
      {{ user.name }}
   {% endfor %}
{% endfor %}

But how can I get users with custom functions? For example, I want to list users with some options and sorted by date like this:

{% for user in category.verifiedUsersSortedByDate %}

I wrote custom function for this inside UserRepository.php class and tried to add it into Category.php class to make it work. However I got the following error:

An exception has been thrown during the rendering of a template ("Warning: Missing argument 1 for Doctrine\ORM\EntityRepository::__construct(),

2

2 Answers

3
votes

It's much cleaner to retrieve your verifiedUsersSortedByDate within the controller directly and then pass it to your template.

//...
 $verifiedUsersSortedByDate = $this->getYourManager()->getVerifiedUsersSortedByDate();

return $this->render(
    'Xxx:xxx.xxx.html.twig',
    array('verifiedUsersSortedByDate' => $verifiedUsersSortedByDate)
);

You should be very carefull not to do extra work in your entities. As quoted in the doc, "An entity is a basic class that holds the data". Keep the work in your entities as basic as possible and apply all the "logic" within the entityManagers.

If you don't want get lost in your code, it's best to follow this kind of format, in order (from Entity to Template)

1 - Entity. (Holds the data)

2 - Entity Repositories. (Retrieve data from database, queries, etc...)

3 - Entity Managers (Perform crucial operations where you can use some functions from your repositories as well as other services.....All the logic is in here! So that's how we can judge if an application id good or not)

4 - Controller(takes request, return responses by most of the time rendering a template)

5 - Template (render only!)
0
votes

You need to get the users inside your controller via repository

$em = $this->getDoctrine()->getEntityManager();
$verifiedusers = $em->getRepository('MYBundle:User')->getVerifiedUsers();

 return array(
            'verifiedusers'      => $verifiedusers,
                   );
    }