在 "Backend\UsuariosBundle\Entity\Usuario "类中,属性 "group "不是公共的。也许你应该创建 "setGroups() "方法?[英] Property "groups" is not public in class "Backend\UsuariosBundle\Entity\Usuario". Maybe you should create the method "setGroups()"?

本文是小编为大家收集整理的关于在 "Backend\UsuariosBundle\Entity\Usuario "类中,属性 "group "不是公共的。也许你应该创建 "setGroups() "方法?的处理/解决方法,可以参考本文帮助大家快速定位并解决问题,中文翻译不准确的可切换到English标签页查看源文。

问题描述

我有这个问题,我无法解决.我是Symfony 2的新手. 我解释我的问题.我有一个Usuario课程和小组课.我已经覆盖了注册表以将组添加到用户.

这是我的代码

<?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';
    }
}

和我的Usuario类是:

<?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;
    }
}

表格正确显示但在保存时显示此错误: 属性"组"在类中不公开"后端\ usuariosbundle \ entity \ usuario".也许您应该创建方法" setGroups()"?

为什么?一些帮助/想法?

感谢您的帮助.

推荐答案

我想您的经验不足可以扩展到PHP和编程.
但是,我们在这里为您提供帮助.

正如错误所说的那样(当错误确实在说话时是一个幸运的情况)您缺少一种称为setGroups()

的方法

您应该以以下方式实施它

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

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

        return $this;
    }

此方法与类的现有方法截然不同,称为addGroup;使用addGroup,您可以扩展现有的组数组,而使用setGroups()则将所有组放入一个arrayCollection,如果以前相关联的其他组,它们将被覆盖.

symfony2表单引擎默认情况下将使用setXXXX(其中XXXX是您要添加的XXXX)方法,因此对实现它们至关重要.

其他推荐答案

@doncallisto有些正确,但是您的问题更容易解决并且有不同的原因.

另外,如果您添加了一个setGroup(),那么您可能会遇到ArrayCollection vs a PersisitentCollection的问题,然后再出路.解决方案变得凌乱.

Symfony在这里期望的是,您要拥有方法addGroups()和removeGroups(). 复数.您有addGroup()和removeGroup().

我相信,如果您在添加这些行之前生成getters/setters/adder,则会发生这种情况,这些行告诉Symfony以倍数对待它:

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

基本上,它认为您一次只会期望一组,因此它可以语法设置Getters/Setter.这发生了变化,Symfony的语法使用情况也是如此,但是方法名称保持不变.

其他推荐答案

它是自动启动的,也许您可​​以添加:

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

        return $this;
    }

本文地址:https://www.itbaoku.cn/post/2090844.html

问题描述

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.

推荐答案

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.

其他推荐答案

@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.

其他推荐答案

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;
    }