13

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.

Nelluk
  • 1,171
  • 2
  • 12
  • 23

3 Answers3

42

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

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

Nelluk
  • 1,171
  • 2
  • 12
  • 23
12

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);
         }
     }
}
Diego
  • 709
  • 7
  • 18
7

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

...

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

...
Community
  • 1
  • 1
Czar Pino
  • 6,258
  • 6
  • 35
  • 60
  • 1
    Right, but the default value I want is not static, it requires some logic. I might be able to do it in Twig, but doing it in the controller would make more sense to me. – Nelluk Oct 18 '13 at 11:06
  • Can't this be done in just a line instead of one line per field? – S. Dre Apr 18 '22 at 15:13