Symfony 3 Form EntityType不会从对象预填充

时间:2016-10-25 15:33:04

标签: symfony doctrine-orm symfony-forms query-builder

我的选择又名实体类型:类没有预填充选择选项。

我有一个"合同" -Entity,其值为:

object(TradePortalBundle\Entity\Contract)[1206]
 private 'id' => int 26
 private 'classification' => int 25

其中分类(最后)应该是我选择的默认值。 我的表格如下:

$builder
        // Klassifizierung
        ->add('classification', EntityType::class, [
            'class' => 'TradePortalBundle:Dropdowns',
            'query_builder' => function (EntityRepository $entityRepository){
                return $entityRepository->createQueryBuilder('d')
                     // select only the right section
                    ->where('d.dropdown_id = 1');
            },
            'choice_label' => 'label',
            'choice_translation_domain' => 'messages',
            'label' => 'contract.form.label.classification'
        ])
};

public function configureOptions(OptionsResolver $resolver)
{
    $resolver->setDefault('data_class', 'TradePortalBundle\Entity\Contract');
}

并在我的控制器中初始化合同实体:

 /* @var $user User */
 $user = $this->getUser();
 $contract = !$user->getContract() ? new Contract() : $user->getContract();
 $form = $this->createForm(ContractType::class, $contract);
 $form->handleRequest($request);

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

 #var_dump($contract);die;

 $this->getDoctrine()->getManager()->persist($contract);
 $this->getDoctrine()->getManager()->flush($contract);
}

当我坚持合同实体时,一切都很好,价值被保存在实体中。但是它不能预先选择吗? 我希望id 25的选择是预先填写的,但是选择了第一个选项。

1 个答案:

答案 0 :(得分:0)

我认为这是因为您的TradePortalBundle\Entity\Contract必须在classification字段中不是id,而是实体

object(TradePortalBundle\Entity\Contract)[1206]
 private 'id' => int 26
 private 'classification' => object(TradePortalBundle\Entity\Classification [XXX]
     private 'id' => int 25