如何创建多个ChoiceType-Symfony中的行

时间:2019-02-07 16:22:56

标签: php mysql symfony

我有一个多个EntityType,它从数据库中获取他的值,如下所示:

MyFormType.php

 private $membersRepository;

 public function __construct(MembersRepository $membersRepository)
 {
    $this->membersRepository = $membersRepository;
 }

 public function buildForm(FormBuilderInterface $builder, array $options)
 {
    $builder
        ->add('trainer', EntityType::class, [
            'multiple' => true,
            'expanded' => true,
            'class' => Members::class,
            'choices' => $this->membersRepository->findAllByExecutive(),
            'placeholder' => 'Ausbilder',
            'label' => 'Ausbilder',
            'attr'=> array('class'=>'form-control'),
            ])

我的带有findAllByExecutive()的存储库

 /**
 * @return Members[]
 */
public function findAllByExecutive()
{
    return $this->createQueryBuilder('u')
    ->select('partial u.{id, firstname, lastname}')
        ->orderBy('u.lastname', 'ASC')
        ->add('where', 'u.executive = 1')
        ->getQuery()
        ->execute();
}

最后是我的控制器,将这些值放入数据库

 if ($form->isSubmitted() && $form->isValid()) {

        /** @var Dienstbuch $dienstbuch */
        $dienstbuch = $form->getData();
        //dd($dienstbuch->trainer);
        $em->persist($dienstbuch);
        $em->flush();
        $this->addFlash('success', 'Eintrag gespeichert');

        return $this->redirectToRoute('dienstbuch.neu');
    }
  1. 为什么我的方法findAllByExecutive()给我的收益要多于我预期的3行?!
  2. 我如何为每个用户行构建3个复选框?我只给用户一个复选框。我已经阅读了许多小时,文档,帖子,但是我找不到解决方案。希望您能为我提供链接或想法。

1 个答案:

答案 0 :(得分:0)

尝试

/**
 * @return Members[]
 */
public function findAllByExecutive()
{
   return $this->createQueryBuilder('u')
        ->select('partial u.{id, firstname, lastname}')
        ->orderBy('u.lastname', 'ASC')
        ->add('where', 'u.executive = 1')
        ->getQuery()
        ->setHint(Doctrine\ORM\Query::HINT_FORCE_PARTIAL_LOAD, 1)
        ->execute();
    }