Answer the question
In order to leave comments, you need to log in
How to get unique value of fields in Symfony EntityType?
I have a form built with Symphony's Form Component. There is a table that stores certain localizations and cities in which these localizations are located, and there can be several localizations in one city, for example:
$builder
->add('citySelector', EntityType::class, [
'class' => Location::class,
'expanded' => false,
'multiple' => false,
'query_builder' => function (EntityRepository $repository) {
return $repository
->createQueryBuilder('l')
->orderBy('l.addressCity', 'ASC')
->distinct();
},
'choice_label' => 'addressCity',
'attr' => [
'class' => 'form-control'
],
'label' => 'warehouse_filter_form.city',
'placeholder' => 'warehouse_filter_form.any',
'required' => false,
])
Answer the question
In order to leave comments, you need to log in
Generally speaking, you'd be better off normalizing the location table and moving the cities into a separate City entity.
The DISTINCT statement applies to the entire dataset and would not work in your case. Yes, and there is no analogue in QueryBuilder. See https://www.doctrine-project.org/api/dbal/2.6/Doct...
It will be correct as Denis Derepko advises above , i.e. use QueryBuilder#groupBy :
$repository
->createQueryBuilder('l')
->orderBy('l.addressCity', 'ASC')
->groupBy('l.addressCity');
I solved the problem as follows:
1) I defined the form as a service and passed EntityManagerInterface as an argument
2) I used ChoiceType instead of EntityType and put the request into a separate method
As a result, it turned out like this
$builder
->add('citySelector', ChoiceType::class, [
'choices' => array_flip($this->getCitiesArray()),
'expanded' => false,
'multiple' => false,
'attr' => [
'class' => 'form-control'
],
'label' => 'warehouse_filter_form.city',
'placeholder' => 'warehouse_filter_form.any',
'required' => false,
])
private function getCitiesArray()
{
$cities = [];
$results = $this->em->createQueryBuilder()
->select('l.addressCity')
->from(Location::class, 'l')
->groupBy('l.addressCity')
->orderBy('l.addressCity', 'ASC')
->getQuery()
->getArrayResult();
foreach ($results as $result) {
if (!in_array($result['addressCity'], $cities)) {
$cities[$result['addressCity']] = $result['addressCity'];
}
}
return $cities;
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question