php - Symfony2 Twig Get Total Count for Child Entity -


the following entities exist, farm, barn , animals. farm can have many barns , barn many animals.

when displaying farm in twig template number of animals should shown well.

what best way this?

i have create twig extension allows me show number of barns.

public function totalfieldfilter($data, $getfield='gettotal') {     $total = count($data->$getfield());     return $total; } 

in template use {{ farm|totalfield('getbarns') }}, extend write custom function so:

public function totalfieldfilter($farm) {     $total = 0;     foreach($farm->getbarns() $barn) {         $total += count($barn->getaniamls());     }     return $total; } 

although work, there better way , can made more generic? if wanted count legs on animals? or how many doors barn has, have write custom twig extension each time.

use entity accessors :

{% farm in farms %}    {{ farm.name }}    {% set barns = farm.getbarns() %}    barns count = {{ barns|length }}    {% barn in barns %}      {% set animals = barn.getanimals() %}      {{ barn.name }} animals count : {{ animals|length }}    {% endfor %}  {% endfor %} 

Comments

Popular posts from this blog

javascript - RequestAnimationFrame not working when exiting fullscreen switching space on Safari -

Python ctypes access violation with const pointer arguments -