lookbadgers
lookbadgers

Reputation: 988

Symfony2 Twig Get Total Count for Child Entity

The following entities exist, Farm, Barn and Animals. A Farm can have many Barns and a Barn many Animals.

When displaying a Farm in a TWIG template the number of Animals should be shown as well.

What is the best way to do this?

I have create a TWIG extension which allows me to easily show the number of barns.

public function totalFieldFilter($data, $getField='getTotal') {
    $total = count($data->$getField());
    return $total;
}

In my template I would use {{ farm|totalField('getBarns') }}, I could easily extend this to write another custom function like so:

public function totalFieldFilter($farm) {
    $total = 0;
    foreach($farm->getBarns() AS $barn) {
        $total += count($barn->getAniamls());
    }
    return $total;
}

Although this would work, is there a better way and can it be made more generic? What if I wanted to count Legs on Animals? Or how many Doors a Barn has, I would have to write a custom TWIG extension each time.

Upvotes: 2

Views: 2530

Answers (2)

David Jacquel
David Jacquel

Reputation: 52829

Use Entity accessors :

{% for farm in farms %}

  {{ farm.name }}

  {% set barns = farm.getBarns() %}

  Barns count = {{ barns|length }}

  {% for barn in barns %}

    {% set animals = barn.getAnimals() %}

    {{ barn.name }} animals count : {{ animals|length }}

  {% endfor %}

{% endfor %}

Upvotes: 3

MrGlass
MrGlass

Reputation: 9262

You are looking for the length filter

When used with an array, length will give you the number of items. So, if your array is farm.barns, you can just use {{ farm.barns|length }}

Upvotes: 2

Related Questions