I'm trying to display a table, in which the user will decide which objets will be shown by selecting different options in a form.
if ($form->isValid()) {
$type = $form->get('type')->getData();
//Getting values from Array $type returned by getData on the form
foreach ($type as $livraison) {
$elements = $this->getDoctrine()
->getManager()
->getRepository('etaqenregistrementBundle:Livraison')
->findBy(array('type' => $livraison));
}
}
If we selected two options, $type will be an array which contains two different objects $livraison (var_dump($livraison) in the foreach statement ) :
object(etaq\adminBundle\Entity\typeLivraison)[434] private 'id' => int 1 private 'valeur' => string 'Interne' (length=7)
object(etaq\adminBundle\Entity\typeLivraison)[436] private 'id' => int 3 private 'valeur' => string 'Autorité' (length=9)
But findBy method returns only one object, the one which was selected first in the form.
What I want is to sort on ONE parameter if user selected one in the form, or to sort on TWO if he selected two, or three ... etc
Here is my form :
$form = $this->createFormBuilder()
->add('ecart', 'choice', array(
'label' => 'Only late :',
'choices' => array(true => 'Yes', false => 'No'),
'multiple' => false,
'expanded' => true,
'required' => true,
'empty_data' => false))
->add('type', 'entity', array(
'label' => ' Type :',
'class' => 'etaqadminBundle:typeLivraison',
'empty_data' => false,
'required' => true,
'property' => 'valeur',
'multiple' => true,
'expanded' => true))
->getForm();
Thanks guys.
findBy can return multiple values:
If you pass an array of values Doctrine will convert the query into a WHERE field IN (..) query automatically: Doctrine 2 Docs.
Get all ids, and afterwards, send them all into the findBy.
if ($form->isValid()) {
$type = $form->get('type')->getData();
$livRaisonsIds = array();
//Getting values from Array $type returned by getData on the form
foreach ($type as $livraison) {
// Something similar, there might be a setter to get the id since its private.
$livRaisonsIds[] = $livraison->id;
}
$elements = $this->getDoctrine()
->getManager()
->getRepository('etaqenregistrementBundle:Livraison')
->findBy(array('type' => $livRaisonsIds));
}
You can use query (http://docs.doctrine-project.org/en/latest/reference/dql-doctrine-query-language.html) or query builder (http://docs.doctrine-project.org/en/latest/reference/query-builder.html)
$qb = $this->getDoctrine()
->getManager()
->createQueryBuilder();
$elements = $qb->from('etaqenregistrementBundle:Livraison', 'l')
->select('l')
->where(qb->expr()->in('l.type', ':ids'))
->setParameter('ids', $livraisonIds)
->getQuery()
->getResult();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With