What i have
I have a database table usuario (user) and a table perfil (profile), connected with a perfiles_usuario (profiles_users) table. A many-to-many relationship. I can now succesfully retrieve the profiles from a user by doing: $perfiles = $usuario->getPerfiles();
/**
*
* @return Perfil[]
*/
function getPerfiles()
{
$perfiles = $this->getPerfilesCollection()->toArray();
return $perfiles;
}
What I'm trying to do
I'm trying to make form where you can add one or more existing profiles from the perfil (profile) table. I would like to have a multiple select field and select the profiles for the user.
What I tried to do
My form builder
class UsuarioType extends AbstractType
{
/**
* @param FormBuilderInterface $builder
* @param array $options
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('username', 'text', array('required' => false))
->add('perfiles', 'entity', array(
'class' => 'UsuarioBundle:Perfil',
'em' => 'dynamic_em',
'query_builder' => function(EntityRepository $er){
return $er->createQueryBuilder('c')->orderBy('c.nombre', 'ASC');
},
'required' => false
))
;
}
My view
<div class="clearfix">
{{ form_widget(formulario.perfiles, { 'attr': { 'class': 'select-perfiles', 'multiple':'' } }) }}
</div>
My error:
Catchable Fatal Error: Argument 1 passed to
Centro\UsuarioBundle\Entity\Usuario::setPerfiles() must be of the type array,
object given, called in C:\....\vendor\symfony\symfony\src\Symfony\Component\PropertyAccess\PropertyAccessor.php
on line 345 and defined in C:\....\src\Centro\UsuarioBundle\Entity\Usuario.php line 450
Usuario.php line 450
public function setPerfiles(array $perfiles) // line 450
{
# Borra los perfiles que tiene el usuario
$this->getPerfilesCollection()->clear();
# Asigna los perfiles pasados por parámetro
foreach ($perfiles as $perfil) {
$this->addPerfil($perfil);
}
return $this;
}
I think that the problem is in my user createAction:
$usuario = new Usuario();
$formulario = $this->crearCrearForm($usuario);
$formulario->handleRequest($request); <--------- ... at this line
And this is the Form Data
....
centro_extranetbundle_usuario[username]:test
centro_extranetbundle_usuario[perfiles]:9
centro_extranetbundle_usuario[perfiles]:4