Property “groups” is not public in class “Backend\UsuariosBundle\Entity\Usuario”. Maybe you should create the method “setGroups()”?

£可爱£侵袭症+ 提交于 2019-12-25 02:38:24

问题


I have this problem and I can´t resolve it. I'm newbie in Symfony 2. I explain my problem. I have a Usuario class and Group class. I have overwritten the RegistrationForm to add group to users.

This is my code

<?php

namespace Backend\UsuariosBundle\Form\Type;

use Symfony\Component\Form\FormBuilderInterface;
use FOS\UserBundle\Form\Type\RegistrationFormType as BaseType;

class RegistrationFormType extends BaseType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {


        // agrega tu campo personalizado
        $builder->add('name', 'text', array('label'=>'Nombre Completo de usuario:'));

        parent::buildForm($builder, $options);

        // agrega tu campo personalizado
        $builder->add('roles', 'choice', 
                            array('label' => 'Elige un Rol para el usuario', 'required' => true, 
                                'choices' => array( 1 => 'ROLE_ADMIN', 2 => 'ROLE_USER'), 
                                'multiple' => true))
                ->add('groups', 'entity', array(
                            'label' => 'Asociar al Grupo de',
                            'empty_value' => 'Elija un grupo para el usuario',
                            'class' => 'BackendUsuariosBundle:Group',
                            'property' => 'name',
                        ))


        ;
    }



    public function getName()
    {
        return 'mi_user_registration';
    }
}

And my Usuario class is this:

<?php

namespace Backend\UsuariosBundle\Entity;

use FOS\UserBundle\Entity\User as BaseUser;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;
use \FOS\UserBundle\Model\GroupInterface;
use Doctrine\Common\Collections\ArrayCollection;

/**
 * @ORM\Entity
 * @ORM\Table(name="Usuario")
 * @UniqueEntity(fields="username")
 * @UniqueEntity(fields="email")
 */
class Usuario extends BaseUser
{

    /**
     * @ORM\Column(type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    protected $id;

    /**
     * @ORM\Column(type="string", length=50)
     *
     * @Assert\NotBlank(message="Por favor, introduce tu nombre.", groups={"Registration", "Profile"})
     * @Assert\MinLength(limit="3", message="El nombre es demasiado corto.", groups={"Registration", "Profile"})
     * @Assert\MaxLength(limit="50", message="El nombre es demasidado largo.", groups={"Registration", "Profile"})
     */
    protected $name;

    /**
     * @ORM\ManyToMany(targetEntity="Backend\UsuariosBundle\Entity\Group")
     * @ORM\JoinTable(name="fos_user_user_group",
     *      joinColumns={@ORM\JoinColumn(name="user_id", referencedColumnName="id")},
     *      inverseJoinColumns={@ORM\JoinColumn(name="group_id", referencedColumnName="id")}
     * )
     */
    protected $groups;

    public function __construct() {
        $this->groups = new ArrayCollection();
        parent::__construct();
    }

    /**
     * Set name
     *
     * @param string $name
     * @return Usuario
     */
    public function setName($name)
    {
        $this->name = $name;

        return $this;
    }

    /**
     * Get name
     *
     * @return string 
     */
    public function getName()
    {
        return $this->name;
    }


    /**
     * Agrega un rol al usuario.
     * @throws Exception
     * @param Rol $rol 
     */
    public function addRole( $rol ) {
        $this->roles = array();
        if($rol == 1) {
          array_push($this->roles, 'ROLE_ADMIN');
        }
        else if($rol == 2) {
          array_push($this->roles, 'ROLE_USER');
        }
    }


    /**
     * Get id
     *
     * @return integer 
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Add groups
     *
     * @param \FOS\UserBundle\Entity\Group $groups
     * @return Usuario
     */
    public function addGroup(GroupInterface  $groups)
    {
        $this->groups[] = $groups;

        return $this;
    }

    /**
     * Remove groups
     *
     * @param \FOS\UserBundle\Model\GroupableInterface $groups
     */
    public function removeGroup(GroupInterface  $groups)
    {
        $this->groups->removeElement($groups);
    }

    /**
     * Get groups
     *
     * @return \Doctrine\Common\Collections\Collection 
     */
    public function getGroups()
    {
        return $this->groups;
    }
}

Form shows correctly but at save show me this error: Property "groups" is not public in class "Backend\UsuariosBundle\Entity\Usuario". Maybe you should create the method "setGroups()"?

Why? Some help/ideas?

Thanks for your help.


回答1:


I suppose that your inexperience could extend to PHP and programming in general.
However, we're here to help you.

As error says to you (is a lucky case when the error is really speaking) you're missing a method called setGroups()

You should implement it, in the following way

    /**
     * Set groups
     *
     * @param Doctrine\Common\Collections\ArrayCollection $groups
     * @return Usuario
     */

    public function setGroups(ArrayCollection  $groups)
    {
        $this->groups = $groups;

        return $this;
    }

This method is deeply different from existing method of your class, called addGroup; with addGroup you extend existing array of groups, whereas with setGroups() you put all groups into an ArrayCollection and, if other groups previously was associated, they will be overwritten.

Symfony2 form engine will work, by default, with setXXXX (where XXXX is property you're going to add) methods so is vital to implement them.




回答2:


@DonCallisto is somewhat right, but your issue is easier to fix and has a different cause.

Also, if you add a setGroup(), then you risk running into an issue with an ArrayCollection vs a PersisitentCollection later down the road. The fixes for that become messy.

What Symfony is expecting here, is for you to have the methods addGroups() and removeGroups(). Plural. You have addGroup() and removeGroup().

I believe this happens if you generate the getters/setters/adders BEFORE you added these lines, which tell Symfony to treat it in multiples:

public function __construct() {
    $this->groups = new ArrayCollection();
}

Basically, it thought you would only ever be expecting ONE group at a time, so it set up the getters/setters grammatically. This was changed and so has Symfony's grammar usage, but the method names have stayed the same.




回答3:


it's automapping maybe you can add:

    /**
     * Add groups
     *
     * @param \FOS\UserBundle\Entity\Group $groups
     * @return Usuario
     */
    public function setGroup(GroupInterface  $groups)
    {
        $this->groups[] = $groups;

        return $this;
    }


来源:https://stackoverflow.com/questions/14931624/property-groups-is-not-public-in-class-backend-usuariosbundle-entity-usuario

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!