Condition a form in symfony2?

0

Well, I have the following data in a symfony form:

->add('lugar', EntityType::class, array(
                'class' => 'AppBundle\Entity\Lugar',
                'mapped' => false,
                'query_builder' => function (EntityRepository $er) {
                    return $er->createQueryBuilder('e')
                        ->orderBy('e.horaInicio', 'ASC');
                },
                'choice_label' => 'lugar',
                'label' => 'Desea acudir a las siguientes horas? (15:45-17:00)'
            ))

Currently this code shows me all the hours that there are in horaInicio , I would like to know if there is any way to catch only the ones I show in the code, with a if or some method like that.

    
asked by Alberto Martínez 24.05.2017 в 09:39
source

2 answers

2

Since you use the query_builder parameter, you can use it to filter the elements that will be displayed:

'query_builder' => function (EntityRepository $er) {
     return $er->createQueryBuilder('e')
               ->where(/* tu condición aquí */)
               ->orderBy('e.horaInicio', 'ASC');
},

For example, to use a range of dates:

'query_builder' => function (EntityRepository $er) {
     return $er->createQueryBuilder('e')
               ->where('e.date > :datetimeStart') // Campo fecha es mayor que...
               ->andWhere('e.date < :datetimeEnd') // Campo fecha es menor que...
               ->setParameter('datetimeStart', new \DateTime('now')) // mayor que hoy
               ->setParameter('datetimeEnd', new \DateTime('tomorrow')) // menor que mañana
               ->orderBy('e.horaInicio', 'ASC');
},
    
answered by 25.05.2017 / 09:30
source
1

Another way that you can use (based on Muriano's) is to pass the querybuilder parameters defined before the form. for example:

'query_builder' => function (EntityRepository $er) use ($start, $end) {
     return $er->createQueryBuilder('e')
    ->where('e.date > :datetimeStart')
    ->andWhere('e.date < :datetimeEnd')
    ->setParameter('datetimeStart', $start)
    ->setParameter('datetimeEnd', $end) // menor que mañana
    ->orderBy('e.horaInicio', 'ASC');
},

$ start and $ end must be defined before calling the add of the field you are defining.

    
answered by 25.05.2017 в 12:28