marosffy
marosffy

Reputation: 23

Define custom method and access it from twig

I have two entities in 1:n relations: Race and Day - a race may have more days. This is the simple model:

Race (id)

Day (id, race_id, is_active, is_deleted)

I want to access the superior one - Race - within a Symfony2 project via Doctrine and display results in a Twig template. For the direct Race attributes it is easy.

However, it becomes trickier, when I want to use a custom defined method (sort of flag, let's call it hasActiveDays()) in Race that reflects if the race had any active and not deleted days. Simple Doctrine relation would not be enough, so I need to use a query like this:

SELECT d FROM mtboLibBundle:Day d WHERE d.isActive = 1 AND d.isDeleted = 0 AND d.raceId = :id

My question is basicly where/how to implement this query and how to invoke it in a twig template? Anything I tried resulted various errors so far, so I'd be grateful if someone could help.

I.e. this was a try:

class RaceRepository extends EntityRepository {
    public function hasActiveDays() {
        $em = $this->getEntityManager();
        $query = $em->createQuery('SELECT f FROM mtboLibBundle:Day d
            WHERE d.isActive = 1
            AND d.isDeleted = 0
            AND d.raceId = :id')
                ->setParameter('id', $this->id)
                ;
        $days = $query->getResult();
        return (count($days) == 0) ? false : true;
    }
}

Method does not exist - when called from the template:

{{ race.hasActiveDays }}

Upvotes: 1

Views: 997

Answers (1)

Delford Chaffin
Delford Chaffin

Reputation: 623

I don't think you'll be able to call a function in a repository the way you are trying to do. One thing I've done is put a function on the entity class and you can call that from your template.

In your Race class:

public function hasActiveDays(){
    // here, perhaps pull all of the days for this race - maybe from a doctrine relation
    // loop through, filter, etc.
    // return whatever is appropriate
}

... then, in your template, you'll be able to call that function the way you are trying to above.

Upvotes: 1

Related Questions