-
Notifications
You must be signed in to change notification settings - Fork 9
Using Forms With And Without Objects
While working on/looking at the code for Might & Fealty there are times you'll notice that forms are either created in the controller or loaded from file. If they're loaded from file it'll look like this:
$form = $this->createForm(new RealmOfficialsType($candidates, $position->getHolders()));
Whereas, if it's created in the controller it'll usually be something shorter, or something that doesn't justify the creation of an entire FormType being created for it like this:
$form = $this->createFormBuilder()
->add('sure', 'checkbox', array(
'required'=>true,
'label'=>'realm.abolish.sure',
'translation_domain' => 'politics'
))
->getForm();
$form->handleRequest($request);
Interestingly, when working with the data from both of these, it'll be in an array, rather than as an object, as no object is being passed to either of the form builders. It'll always be:
$data = $form->getData(); $variable->setAttribute($data['stuff']);
Alternatively you can pass an object to a form, like so:
$form = $this->createForm(new CharacterSettingsType(), $character);
Note the $character AFTER the "CharacterSettingsType()" but still in the createForm paranthesis? This is how you pass an object to the form. This has a couple added benefits. Firstly, you have no requirement to do manual $var->setAttr($data['thing']) anymore, as the Symfony2 framework has built in understanding that if you built a form that has field that match object attributes, you want to edit those attributes with the submiited data. It also understands that you only care to edit the data points the form requested, and it'll automatically populate those data points with whatever is appropriate for that object.
The downside of this is that you can't, easily, build a form to handle the relevant data of multiple objects or a form that handles both an object and associated object's data (as is the case with much of the Description editing fields). To do this you'd need to pass an object as a variable into the form, then subload a form within the form with that variable now passed as an object to the new form.