Filter Doctrine collections

Let's assume the following scenario where you have a Product entity linked to a Category entity by a ManyToOne relationship.

In your twig template you want to loop on all categories and display a list of products for each of them. The {{ category.products }} will give you that ... no problem. Now imagine you want to retrieve only active products ordered by position. Since it is not good practice to call the Doctrine Entity Manager in your entity, here comes Doctrine Criteria Filters to the rescue.

In your Category entity create the following method

public function getActiveProducts()
    {
        $criteria = Criteria::create()
            ->where(Criteria::expr()->eq("enabled", 1))
            ->andWhere(Criteria::expr()->eq("category", $this))
            ->orderBy(array("position" => Criteria::ASC));

        return $this->getProducts()->matching($criteria);
    }

To loop on your active and ordered products you can now call the method like this in your twig template

{% for product in category.activeProducts %}

[...]

{% endfor %}

More information on the Doctrine documentation.