The best way to populate select form element with Project entities is to use entity form field. So you don't have to pass any options to form type class.
$builder
->add('project', 'entity', [
'label' => 'form.project',
'class' => 'AppBundle\Entity\Project',
'property' => 'name',
'required' => true,
'empty_value' => 'form.select_empty_value',
'query_builder' => function($repository) {
return $repository->createQueryBuilder('p')->add('orderBy', 'p.name ASC');
},
])
;
If you need to populate choice field there is another best practice. You should define your form type class as service and inject Entity Manager into it. So you could fetch any data from the database and populate any choice fields.
services.xml
<service id="app.form.modifier_supprimer_projet" class="AdminBundle\Form\ModifierSupprimerProjet">
<tag name="form.type" alias="app_modifier_supprimer_projet" />
<argument type="service" id="doctrine.orm.entity_manager"/>
</service>
ModifierSupprimerProjet.php
<?php
namespace AppBundle\Form;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
use Doctrine\ORM\EntityManager;
class ModifierSupprimerProjet extends AbstractType
{
/**
* @var EntityManager
*/
protected $em;
/**
* @param EntityManager $em
*/
public function __construct(EntityManager $em)
{
$this->em = $em;
}
/**
* @param FormBuilderInterface $builder
* @param array $options
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('project', 'choice', [
'label' => 'form.project',
'choices' => $this->em->getRepository('AppBundle:Project')->getProjectsList(),
])
;
}
/**
* @param OptionsResolverInterface $resolver
*/
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults([
'data_class' => 'AppBundle\Entity\ModifierSupprimerProjet',
]);
}
/**
* @return string
*/
public function getName()
{
return 'app_modifier_supprimer_projet';
}
}
Controller
$modifierSupprimerProjet = new ModifierSupprimerProjet();
$form = $this->createForm('app_modifier_supprimer_projet', $modifierSupprimerProjet);
Second param of createForm method is Entity, if your form is mapped to any entity.