Symfony2 - установить значение флажков в форме из ORM DQL

Я создаю форму, которая должна фильтровать пользовательский список запросов в Symfony2 (версия 2.3) с помощью LexikFilter Bundle.
Настройка проекта:

  1. Symfony2: 2.3.7
  2. Комплект LexikFilter: 3.0.8
  3. Доктрина ОРМ 2.4

Проект состоит из сущностей, имеющих отношение n:m (родители-обучение), форма родительского фильтра включает форму фильтра обучения, как показано ниже:

class MyParentsType extends AbstractType
{

    private $repository ;

    function __construct($repository)
    {
        $this->repository = $repository; // store it, we are going to use it later
    }

    public function getName()
    {
        return 'parents_filter';
    }

    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder->add('Firstname', 'filter_text', array('condition_pattern' => FilterOperands::STRING_BOTH,))
                ->add('Lastname', 'filter_text', array('condition_pattern' => FilterOperands::STRING_BOTH,))
                ->add('trainings','filter_collection_adapter', array(
                                            'type'=> new MyTrainingType2($this->repository),
                                            'default_data' => new ArrayCollection(),
                                            'add_shared'=> function(FilterBuilderExecuterInterface $qbe){
                                                $closure = function(QueryBuilder $filterBuilder, $alias, $joinAlias, Expr $expr){
                                                     $filterBuilder ->leftJoin($alias.'.options',$joinAlias);
                                                };
                                                $qbe->addOnce($qbe->getAlias().'.options','opt',$closure);
                                            },
                ));
    }

    public function setDefaultOptions(OptionsResolverInterface $resolver)
    {
        $resolver->setDefaults(
            [
                'data_class' =>'tuto\LexikTestBundle\Entity\Parents',
                'csrf_protection' => false,
                'validation_groups' => ['filtering'] // avoid NotBlank() constraint-related message
            ]
        );
    }

и форма фильтра обучения:

class MyTrainingType2 extends AbstractType
{

    private $repository ;

    function __construct($repository)
    {
        $this->repository = $repository; // store it, we are going to use it later
    }


    public function getName()
    {
        return 'training_filter';
    }

    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder->add('Title', 'filter_text', array('condition_pattern' => FilterOperands::STRING_BOTH,))
                ->add('Location', 'filter_choice', array( 'choice_list' => new ChoiceList($this->repository->getLocationList(),$this->repository->getLocationList()),
                                                          'expanded'=> true,
                                                          'multiple'=>true,
                                                          )
                    );

    }

    public function setDefaultOptions(OptionsResolverInterface $resolver)
    {
        $resolver->setDefaults(
            [
                'data_class' =>'tuto\LexikTestBundle\Entity\Training',
                'csrf_protection' => false,
                'validation_groups' => ['filtering'] // avoid NotBlank() constraint-related message
            ]
        );
    }
}  

Вот метод getLocationList() для Training Repository:

 public function getLocationList()
    {   $qb = $this->createQueryBuilder('t')
        ->select('t.Location')//
        ->orderBy('t.Location','asc')
        ->distinct(true);

        return $qb->getQuery()->getArrayResult();
    }

Фильтр отображает флажки, но в поле значения установлено имя столбца Location. Здесь фрагмент массива, возвращаемый getArrayResult

array (size=199)
  0 => 
    array (size=1)
      'Location' => string '‘Arīshah' (length=11)
  1 => 
    array (size=1)
      'Location' => string 'Abuja' (length=5)

Я хотел бы вернуть его как:

 0 => 
    array (size=1)
      '‘Arīshah' => string '‘Arīshah' (length=11)
  1 => 
    array (size=1)
      'Abuja' => string 'Abuja' (length=5)

person Raymond A    schedule 19.02.2016    source источник


Ответы (1)


Ты можешь попробовать:

$locations = array_map(function(array $location){
                 return $location['Location'];
             }, $this->repository->getLocationList());

// and then in your form definition:

'choice' => ['choices' => array_combine($locations, $locations)]
person hasumedic    schedule 19.02.2016
comment
Можете ли вы немного расширить приведенный код? потому что я создал класс Location с одноименным полем. Однако я получаю сообщение об ошибке, говорящее о том, что Closure expect Type of Location but array given - person Raymond A; 19.02.2016
comment
Извините, я предположил, что ваш репозиторий возвращает какую-то сущность Location. Что это за репозиторий и какой массив возвращается при вызове getLocationList()? - person hasumedic; 19.02.2016
comment
Вложенный массив (я обновил вопрос с возвращаемым типом массива и используемым DQL). - person Raymond A; 19.02.2016
comment
Я немного изменил ответ - person hasumedic; 19.02.2016