0

I have an entity field type in my form, but then when I try to get the values from the controller I get an error.

This is my form builder

$builder
        ->add('recursos', 'entity', array(
                'class' => 'SIGIConvocatoriasBundle:Recurso',
                'property' => 'nombre',
                'multiple' => true,
                'mapped' => false
                ))
        ->add('requisitos', 'entity', array(
                'class' => 'SIGIConvocatoriasBundle:Requisito',
                'property' => 'nombre',
                'multiple' => true,
                'mapped' => false
                ))
    ;

and this is my controller

$entity  = new Convocatoria();
$form = $this->createForm(new ConvocatoriaType(), $entity);
$form->bind($request);
$recursos = $request->request->get('recursos');
foreach ($recursos as $recurso)
{
    //Do something ...
}

But I get an error here

Invalid argument in foreach ...

Like if the $recursos variable is empty or something, and I get a 'recursos' => null in the symfony exception. I'd really appreciate some help here :D

JhovaniC
  • 304
  • 3
  • 17

2 Answers2

1

The request itself contains raw data (scalars). When you bind the request to the form, it will transform this raw data to normalized data. The array of ids will be transformed to an array of entities, and then be passed to $entity->setRecursos(); // or each one to $entity->addRecurso();

$form = $this->createForm(new ConvocatoriaType(), $entity)
$form->bind($request);

$formData = $request->request->get($form->getName());
$formData['recursos']; // should be an array of ids

$entity->getRecursos(); // array of entities
Florian Klein
  • 8,692
  • 1
  • 32
  • 42
0

Try

             $entity  = new Convocatoria();
             $form = $this->createForm(new ConvocatoriaType(), $entity);
             $form->bind($request);

              foreach ($entity->getRecursos() as $recurse) {
                    //do something
                }

             $em = $this->getDoctrine()->getEntityManager();
                $em->persist($entity);
                $em->flush();
Shrujan Shetty
  • 2,298
  • 3
  • 27
  • 44
  • The problem is that the attribute is not mapped, so it's ignored by the `$form->bind($request)` thus I can't use the `$entity->getRecursos` ... xD – JhovaniC Jan 09 '13 at 17:14
  • When mapping forms to objects, all fields are mapped. Any fields on the form that do not exist on the mapped object will result in an exception. – Shrujan Shetty Jan 10 '13 at 04:33
  • If you need extra fields in the form which does not exist in your entity then add ->add('extraField', null, array('property_path' => false)) – Shrujan Shetty Jan 10 '13 at 04:35
  • 1
    as of symfony 2.0.9 `property_path` was replaced by `mapped` as you can see in my form builder. Thanks for your help. – JhovaniC Jan 11 '13 at 15:16