From your example, where you want to get the first result as the prefered choice, you have to return the entity with the first rank and not its index.
To do so, you can retrive it in the controller then pass it as a parameter in $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,
));
//...
}
You can also use getReference
, as j_goldman noted in their comment, but since your ranks can change (I think), I don't think it fit well for your use case:
$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),
));
Finally, you can use a callback returning the chosen entity, for example with the same DQL you used with a limit of 1: (It's what I would do)
$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)
;
},
));