hous
hous

Reputation: 2679

Get length of array with condition on attribute

I'd like if is it possibel to get length of array with condition on attribute without create another query in the controller.

public function pageAction()
{
    $em = $this->getDoctrine()->getManager();
    $pages = $em->getRepository('AppBundle:Page')->findAll();
    return $this->render(':Frontend/includes:menu.html.twig', array(
        'pages' => $pages
    ));
}

in the view

//number of all pages
{{ pages|length }} // output 15 (ok)

now is it possible to get the number of pages where page.activate == true from the same result returned in the controller ?

// number of page where page.activate == true
 ??

Upvotes: 2

Views: 2497

Answers (1)

Alvin Bunk
Alvin Bunk

Reputation: 7764

This should work hous:

{% set pageCount = 0 %}{# Sets variable #}
{% for p in pages if p.getActivate %}
    {% set pageCount = pageCount + 1 %}
{% endfor %}

<p>Activated Pages: {{ pageCount }}

Try it!

Upvotes: 5

Related Questions