I have a form that is bound to an entity, but it also has an extra unmapped field: (from the FormType class)
$builder
->add('name')
->add('qoh')
->add('serialNumber', 'text', array('mapped' => false, 'required' => false))
I want to pre-populate the serialNumber field from the controller with information taken from the request URL. The closest method I have found would be:
$form->setData(mixed $modelData)
but the API does not specify what form '$modelData' takes and nothing I've tried has had any effect.
Someone on Symfony's IRC channel gave me this answer, and they declined to post it here:
$form->get('serialNumber')->setData($serial_number);
You can use Form Events. For example if you want to set the data from the database to a non mapped field you can use POST_SET_DATA:
class AddNonMappedDataSubscriber implements EventSubscriberInterface
{
protected $em;
public function __construct(EntityManager $em)
{
$this->em = $em;
}
public static function getSubscribedEvents()
{
return array(
FormEvents::POST_SET_DATA => 'postSetData'
);
}
public function postSetData(FormEvent $event){
$form = $event->getForm();
$myEntity = $event->getData();
if($myEntity){
$serialNumber = $myEntity->getNumber();
$form->get('serialNumber')->setData($serialNumber);
}
}
}
You can pre-populate the field in twig (Set default value of Symfony 2 form field in Twig).
...
{{ form_widget(form.serialNumber, { value : serialNumber }) }}
...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With