Set Default Choice for EntityType in Symfony Form


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.

Advertisements

About Alvin Bunk
Hi, I'm a software developer at Taft College.

2 Responses to Set Default Choice for EntityType in Symfony Form

  1. Iltar says:

    First of all, you will save yourself a lot of hassle by not binding entities to forms: https://stovepipe.systems/post/avoiding-entities-in-forms Second, you can set the data object when creating the form. And last, you should probably not create this in your controller, but in a dedicated type.

    • Alvin Bunk says:

      Thank you for your feedback Iltar. Good points which I’m aware of. In my case I had a complex form with a lot of Entities and I needed to customize the form. Just showing users how to set the default choice using the ‘data’ option in case anyone ever needs to do that.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: