Click here to Skip to main content
15,867,771 members
Articles / Programming Languages / PHP

Set Default Choice for EntityType in Symfony Form

Rate me:
Please Sign up or sign in to vote.
0.00/5 (No votes)
21 Nov 2016CPOL1 min read 28.8K   1   2
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:

PHP
$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.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer Taft College
United States United States
I’m a software developer. Currently I’m working at Taft College as a Programmer.

Comments and Discussions

 
QuestionRequest more information on $em in your example Pin
Member 1341846219-Sep-17 12:18
Member 1341846219-Sep-17 12:18 
AnswerRe: Request more information on $em in your example Pin
Alvin Bunk24-Sep-17 5:40
professionalAlvin Bunk24-Sep-17 5:40 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.