从您的示例中,您希望获得第一个结果作为首选,您必须返回具有第一排名的实体而不是其索引。
为此,您可以在控制器中检索它,然后将其作为参数传递$options
:
public function buildForm(FormBuilderInterface $builder, array $options)
{
//prevent error if $options['prefered_choices'] is not set
$prefered_choices = isset($options['prefered_choices']) ? $options['prefered_choices'] : array();
$builder->add('candStatus', 'entity', array(
'label' => 'Candidate Status',
'class' => 'AmberAtsBundle:SelCandStatus',
'query_builder' => function(EntityRepository $er) {
return $er->createQueryBuilder('sc')
->orderBy('sc.rank', 'ASC')
;
},
'property' => 'candStatus',
'preferred_choices' => $prefered_choices,
));
//...
}
您也可以使用getReference
,正如 j_goldman在他们的评论中指出的那样,但是由于您的等级可以改变(我认为),我认为它不适合您的用例:
$builder->add('candStatus', 'entity', array(
'label' => 'Candidate Status',
'class' => 'AmberAtsBundle:SelCandStatus',
'query_builder' => function(EntityRepository $er) {
return $er->createQueryBuilder('sc')
->orderBy('sc.rank', 'ASC')
;
},
'property' => 'candStatus',
'prefered_choices' => $this->em->getReference('AmberAtsBundle:SelCandStatus', 1),
));
最后,您可以使用返回所选实体的回调,例如使用与限制为 1 的相同 DQL :(这就是我要做的)
$builder->add('candStatus', 'entity', array(
'label' => 'Candidate Status',
'class' => 'AmberAtsBundle:SelCandStatus',
'query_builder' => function(EntityRepository $er) {
return $er->createQueryBuilder('sc')
->orderBy('sc.rank', 'ASC')
;
},
'property' => 'candStatus',
'preferred_choices' => function(EntityRepository $er) {
return $er->createQueryBuilder('sc')
->orderBy('sc.rank', 'ASC')
->setMaxResults(1)
;
},
));