Search code examples
phpdoctrine-ormrequestsymfony-2.1entities

How to retrieve an array of entities from the reques object?


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


Solution

  • 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