属性“groups”在“Backend \ UsuariosBundle \ Entity \ Usuario”类中不公开。也许你应该创建方法“setGroups()”?

时间:2013-02-18 07:51:56

标签: symfony fosuserbundle

我有这个问题,我无法解决它。我是Symfony 2的新手。 我解释我的问题。我有一个Usuario类和Group类。我已经覆盖了RegistrationForm以向用户添加组。

这是我的代码

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

表单显示正确,但在保存时显示此错误: 属性“groups”在“Backend \ UsuariosBundle \ Entity \ Usuario”类中不公开。也许你应该创建方法“setGroups()”?

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

感谢您的帮助。

3 个答案:

答案 0 :(得分:1)

我认为你缺乏经验可以扩展到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是您要添加的属性)方法,因此对于实现它们至关重要。

答案 1 :(得分:0)

@DonCallisto有点对,但你的问题更容易修复,并且有不同的原因。

此外,如果您添加了一个setGroup(),那么您可能会遇到ArrayCollectionPersisitentCollection之后的问题。对此的修复变得混乱。

Symfony期待的是,您可以使用方法addGroups()removeGroups()复数。您有addGroup()removeGroup()

我相信如果你在添加这些行之前生成getter / setters / adders会发生这种情况,这会告诉Symfony将它处理成倍数:

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

基本上,它认为你一次只能期待一个组,所以它在语法上设置了getters / setter。这已被改变,Symfony的语法用法也是如此,但方法名称保持不变。

答案 2 :(得分:-1)

它的自动化可能你可以添加:

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

        return $this;
    }