Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pre-populate form value of unmapped field

Tags:

symfony

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.

like image 353
Nelluk Avatar asked Oct 17 '13 23:10

Nelluk


3 Answers

Someone on Symfony's IRC channel gave me this answer, and they declined to post it here:

$form->get('serialNumber')->setData($serial_number);

like image 175
Nelluk Avatar answered Oct 20 '22 19:10

Nelluk


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);
         }
     }
}
like image 24
Diego Avatar answered Oct 20 '22 19:10

Diego


You can pre-populate the field in twig (Set default value of Symfony 2 form field in Twig).

...

{{ form_widget(form.serialNumber, { value : serialNumber }) }}

...
like image 7
Czar Pino Avatar answered Oct 20 '22 18:10

Czar Pino