How filter data inside bean object in Symfony 2 and Doctrine
I have two objects: Product
and Feature
. Product
has many others Features
(one to many relationship). Each Feature
has a name and an important status (true if the feature is important, false if not). I want to get all the important features for my product in TWIG.
The solution below is very ugly:
Product: {{ product.name }}
Important features:
{% for feature in product.features %}
{% if feature.important == true %}
- {{ feature.name }}
{% endif %}
{% endfor %}
So, I want to get:
Product: {{ product.name }}
Important features:
{% for feature in product.importantFeatures %}
- {{ feature.name }}
{% endfor %}
I have to filter data in the object object, but how?
// MyBundle/Entity/Vehicle.php
class Product {
protected $features; // (oneToMany)
// ...
protected getFeatures() { // default method
return $this->features;
}
protected getImportantFeatures() { // my custom method
// ? what next ?
}
}
// MyBundle/Entity/Feature.php
class Feature {
protected $name; // (string)
protected $important; // (boolean)
// ...
}
+3
ZaquPL
source
to share
2 answers
You can use the Criteria class to filter the Arraycollection of related functions
class Product {
protected $features; // (oneToMany)
// ...
protected getFeatures() { // default method
return $this->features;
}
protected getImportantFeatures() { // my custom method
$criteria = \Doctrine\Common\Collections\Criteria::create()
->where(\Doctrine\Common\Collections\Criteria::expr()->eq("important", true));
return $this->features->matching($criteria);
}
}
In a branch
Product: {{ product.name }}
Important features:
{% for feature in product.getImportantFeatures() %}
- {{ feature.name }}
{% endfor %}
+4
M khalid junaid
source
to share
You can do this from the repository
$featureEntityRepository->findBy(array(
'impoertant' => true,
'product' => $product->getId()
));
0
Gevorg Margaryan
source
to share