Symfony 3 Form EntityType 不从对象预填充

Symfony 3 Form EntityType doesn't prefill from object

我的选择又名 EntityType:class 不会预填充 select 选项。

我有一个 "contract"-实体,它的值是:

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

where classification (last) 应按我的默认值 selected 选择。 我的表格看起来像:

$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 的选择是预填充的,但第一个选择是 selected.

我认为这是因为您的 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