Many-To-Many and form Symfony2

2019-08-31 06:06发布

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

2条回答
我想做一个坏孩纸
2楼-- · 2019-08-31 06:54

Thanks so much! here is the solution

/**
 * Devuelve una coleccion con los perfiles del usuario
 *
 * @return ArrayCollection
 */
function getPerfiles()
{

    $perfiles = $this->getPerfilesCollection(); # ->toArray(); I delete this
    return $perfiles;
}

Also i change

/**
 * Establece los perfiles del usuario a partir de un ArrayCollection de
 * perfiles
 * 
 * @param ArrayColection
 *
 * @return self
 */
public function setPerfiles(ArrayCollection $perfiles)
{
    // # 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;

    $this->getPerfilesCollection()->clear();

    foreach($collection->toArray() as $perfil){
        $this->addPerfil($perfil);
    }
}

In the form builder i only add this line: 'multiple' => true,

->add('perfiles', 'entity', array(
            'class' => 'UsuarioBundle:Perfil',
            'multiple' => true, <----------------------
            'em' => 'dynamic_em',
            'query_builder' => function(EntityRepository $er){

                return $er->createQueryBuilder('c')->orderBy('c.nombre', 'ASC');

            }, 
            'required' => false
        ))
查看更多
贪生不怕死
3楼-- · 2019-08-31 06:58

First problem: setPerfiles' parameter instance must be of Type collection (Doctrine Interface) Second problem: perfiles is a collection, so you need the collection type in the form and a FormType for Perfiles.

查看更多
登录 后发表回答