I have a select box created with formbuilder:
<select id="form_type" name="form[type]" class="form-control select2 select2-hidden-accessible" tabindex="-1" aria-hidden="true">
<option value="1">text</option>
<option value="2">hidden</option>
<option value="3">password</option>
<option value="4" selected="selected">icon</option>
<option value="5">select</option>
</select>
This is how it is created in my controller:
$formBuilder->add('type', EntityType::class, array(
'attr' => array('class' => 'form-control select2'), 'label' => 'Type',
'class' => FieldTypes::class,
'choice_label' => function ($fieldTypes) {
return $fieldTypes->getName();
}
));
$formBuilder->add('cancel', ButtonType::class, array('label' => 'cancel','attr' => array('class' => 'cancel form-btn btn btn-default pull-right close_sidebar')))
->add('save', SubmitType::class, array('label' => 'Save','attr' => array('id' => 'submit-my-beautiful-form','class' => 'form-btn btn btn-info pull-right','style' => 'margin-right:5px')));
$form = $formBuilder->getForm();
$form->handleRequest($request);
But when I want to save a selection I get the error message:
Argument 1 passed to App\Entity\Fields::setType() must be an instance of App\Entity\FieldTypes or null, string given, called in /Users/work/project/src/Controller/PagesController.php on line 242
In my entity:
public function setType(?FieldTypes $type): self
{
$this->type = $type;
return $this;
}
This is how it it stored:
$entity = $this->getDoctrine()->getRepository($EntityName)->find($data['form[id]']);
$em = $this->getDoctrine()->getManager();
foreach ($fields as $field) {
$em = $this->getDoctrine()->getManager();
$func = 'set'.$field['fieldName'];
$args = $data['form['.$field['fieldName'].']'];
$entity->$func($args);
}
$em->flush();
Use the method $form->handleRequest($request)
. It will populate your form using its configuration (it will instanciate a FieldType
using the posted id).
Here, you add manually the "raw" value of your select, which is string containing the id of your FieldType
.
edit : see the docs