Introduction

I see a lot of postings on stackoverflow about how to use either the EntityType or ChoiceType field for forms when creating a form using the Symfony PHP framework. This is an example of how you can use the ‘data’ option to set the default choice of an EntityType field.

The Form Code

In my case I have an Entity of School which has a `getSchoolId()` getter, which returns the particular School’s ID; which represents the School. So if you wanted to set the default School to a particular value, you can use the following example code:

$form = $this->createFormBuilder()
	...
	->add('school_name', EntityType::class, array(
			'class' => 'AppBundle:School',
			'label' => 'Taken At:',
			'choice_label' => 'school_name',
			'choice_value' => 'school_id',
			'attr' => array('class' => 'school_id'),
			'data' => $em->getReference('AppBundle:School',
					$pet->getCourse()->getSchool()->getSchoolId() ),
	))
	...
	->getForm();
	
...
$form->handleRequest($request);

In the above, $pet represents a petition Entity. So in this case I’m getting the particular School that the course petition belongs to, and in the form it shows that School as the selected value. This is a scenario, where the form allows the user to edit the petition, and in this case edit the School selected from this dropdown list. The dropdown list will show all the Schools available, with the Label as a text School Name, and the selected value will be the Doctrine Entity ID.
You’ll notice the ‘data’ option uses the Entity Manager `getReference()` method, which has two parameters of the Entity and secondly the ID. This sets the default value.