symfony2 选择的选项

Posted

技术标签:

【中文标题】symfony2 选择的选项【英文标题】:symfony2 selected option 【发布时间】:2012-12-29 18:36:56 【问题描述】:

我正在让用户编辑。 我想通过 Users.role_id = UsersRole.id 查看当前用户的选定角色 Users 表有四列(id、username、roleId、descriptions)UsersRole 表有两列 (id,name)

控制器:

public function editAction($id) 
    $user = $this->getDoctrine()
            ->getEntityManager()
            ->getRepository('TruckingMainBundle:Users')
            ->find($id);

    if (!$user) 
        throw $this->createNotFoundException('Unable to find user id.');
    
    $form = $this->createForm(new \Trucking\AdminBundle\Form\UserType(), $user);
    $request = $this->getRequest();

    //save data
    if ($request->getMethod() == 'POST') 
        $form->bindRequest($request);
        if ($form->isValid()) 
            $em = $this->getDoctrine()->getEntityManager();
            $em->persist($user);
            $em->flush();
            return $this->redirect($this->generateUrl('tracking_admin_users'));
        
    
    return $this->render('TruckingAdminBundle:user:edit.html.twig', array(
                'id' => $id,
                'form' => $form->createView()
                    )
    );

UserType.php

    public function buildForm(FormBuilderInterface  $builder, array $options) 

     $builder
        ->add('roleId', 'entity', array(
                'class' => 'TruckingMainBundle:UsersRole',
                'property' => 'name'
        ))
        ->...->..
    

我不知道如何在该列表中设置选定(默认)值,我已经尝试了 5 个小时,但仍然没有结果我使用过 preferred_choices , query_builder -> 我可以通过 critreia 选择(但我不需要)http://symfony.com/doc/current/reference/forms/types/entity.html

我可以打印我当前的用户 ID -> print_r($user->getRoleId()); 我已经有了。 我的“用户”实体与 UserRole 实体有关联用户实体

namespace Trucking\MainBundle\Entity;

use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Security\Core\User\UserInterface;
/**
 * Trucking\MainBundle\Entity\Users
 *
 * @ORM\Table(name="Users")
 * @ORM\Entity
 */
class Users implements UserInterface

    /**
     * @var integer $id
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="IDENTITY")
     */
    protected $id;

    /**
     * @var string $password
     *
     * @ORM\Column(name="password", type="string", length=15)
     */
    private $password;

    /**
     * @var string $username
     *
     * @ORM\Column(name="username", type="string", length=30)
     */
    private $username;

    /**
     * @var string $description
     *
     * @ORM\Column(name="description", type="string", length=20)
     */
    private $description;

    /**
     * @var string $permissions
     *
     * @ORM\Column(name="permissions", type="string", length=300)
     */
    private $permissions;

    /**
     * @var \DateTime $date
     *
     * @ORM\Column(name="date", type="datetime")
     */
    private $date;

    /**
     * @var integer $role_id
     *
     * @ORM\Column(name="role_id", type="integer")
     */
    private $role_id;

    /**
     * @var integer $company_id
     *
     * @ORM\Column(name="company_id", type="integer")
     */    
    private $company_id;

    /**
     * @ORM\ManyToMany(targetEntity="Company", inversedBy="users")
     *
     */
    protected $companies;

    /**
     * @ORM\OneToOne(targetEntity="UsersRole")
     * @ORM\JoinColumn(name="role_id", referencedColumnName="id")
     */
    protected $roles;

    public function __construct() 
        $this->companies = new ArrayCollection();
    

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

    /**
     * Set password
     *
     * @param string $password
     * @return Users
     */
    public function setPassword($password)
    
        $this->password = $password;

        return $this;
    

    /**
     * Get password
     *
     * @return string 
     */
    public function getPassword()
    
        return $this->password;
    

    /**
     * Set username
     *
     * @param string $username
     * @return Users
     */
    public function setUsername($username)
    
        $this->username = $username;

        return $this;
    

    /**
     * Get username
     *
     * @return string 
     */
    public function getUsername()
    
        return $this->username;
    

    /**
     * Set description
     *
     * @param string $description
     * @return Users
     */
    public function setDescription($description)
    
        $this->description = $description;

        return $this;
    

    /**
     * Get description
     *
     * @return string 
     */
    public function getDescription()
    
        return $this->description;
    

    /**
     * Set permissions
     *
     * @param string $permissions
     * @return Users
     */
    public function setPermissions($permissions)
    
        $this->permissions = $permissions;

        return $this;
    

    /**
     * Get permissions
     *
     * @return string 
     */
    public function getPermissions()
    
        return $this->permissions;
    

    /**
     * Set date
     *
     * @param \DateTime $date
     * @return Users
     */
    public function setDate($date)
    
        $this->date = $date;

        return $this;
    

    /**
     * Get date
     *
     * @return \DateTime 
     */
    public function getDate()
    
        return $this->date;
    

    /**
     * Set role_id
     *
     * @param integer $role
     * @return Users
     */
    public function setRoleId($role_id)
    
        $this->roleId = $role_id;

        return $this;
    

    /**
     * Get role_id
     *
     * @return integer 
     */
    public function getRoleId()
    
        return $this->role_id;
    

    /**
     * Set company_id
     *
     * @param Company $company_id
     * @return Users
     */
    public function setCompany(Company $company_id)
    
        $this->company = $company_id;

        return $this;
    

    /**
     * Get company_id
     *
     * @return integer 
     */
    public function getCompanyId()
    
        return $this->company_id;
    

    public function equals(UserInterface $user) 
        return $this->getUsername() == $user->getUsername();
    

    public function eraseCredentials() 

    

    public function getRoles() 
        return (array)$this->roles->getName();
    

    public function setRoles($role) 
        $this->roles = array($role);
    

    public function getSalt() 

        

UsersRole 实体

namespace Trucking\MainBundle\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * USERS_ROLE
 *
 * @ORM\Table(name="USERS_ROLE")
 * @ORM\Entity
 */
class UsersRole

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

    /**
     * @var string
     *
     * @ORM\Column(name="name", type="string", length=30)
     */
    protected $name;

    /**
     * @var string
     *
     * @ORM\Column(name="description", type="string", length=200)
     */
    protected $description;

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

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

        return $this;
    

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

    /**
     * Set description
     *
     * @param string $description
     * @return USERS_ROLE
     */
    public function setDescription($description)
    
        $this->description = $description;

        return $this;
    

    /**
     * Get description
     *
     * @return string 
     */
    public function getDescription()
    
        return $this->description;
    

用户类型(用于表单)

<?php
namespace Trucking\AdminBundle\Form;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Validator\Constraints;

class UserType extends AbstractType 

    public function buildForm(FormBuilderInterface  $builder, array $options) 

     $builder
        ->add("username","text",array(
                   "label" => "Name",
                       'attr'   =>  array(
                           'class'   => 'input-xlarge',
                       ),
                    'constraints' => new Constraints\Length(array('min' => 3))
                   ))
        ->add('roleId', 'entity', array(
                'class' => 'TruckingMainBundle:UsersRole',
                "label" => "Roles",
                'property' => 'name'
        ))
        ->add("description","text",array(
           "label" => "Description",
               'attr'   =>  array(
                   'class'   => 'input-xlarge'
               ),
                'constraints' => new Constraints\NotBlank()
           ));
    

    public function getName()
    
        return 'trucing_adminbundle_usertype';
    

【问题讨论】:

我不完全确定也懒得去检查,但$builder-&gt;add('roleId', 'entity', array('data' =&gt; 'ROLE_ADMIN')) 应该可以。至少这是您在countrychoice 字段中设置默认值的方式? ***.com/questions/7913086/… 'data' => 'ROLE_USER' 不起作用,我尝试使用 'preferred_choices' => array('ROLE_USER') 并且出现错误:警告:spl_object_hash() 预期参数1为对象,给定字符串 是不是你必须指定 id 而不是 ROLE_USER,例如1?否则,您可以以某种方式操作查询,以便所需的默认值将成为结果集中的第一个条目。可能不是最好的解决方案,但应该可以... 【参考方案1】:

在呈现表单之前设置实体的属性:

if (!$user) 
    throw $this->createNotFoundException('Unable to find user id.');


//THIS IS NEW
$theRole = getRoleEntityFromSomewhereItMakesSense();
$user->setRole($theRole); //Pass the role object, not the role's ID

$form = $this->createForm(new \Trucking\AdminBundle\Form\UserType(), $user);
$request = $this->getRequest();

当您生成表单时,它会自动填充您正在使用的实体的属性。

编辑 改变

->add('roleId', 'entity', array(

->add('roles', 'entity', array(

我不明白你为什么同时拥有 roleIdroles

还要更改以下内容,因为 roles 是单个元素,而不是数组(您有一个一对一的关系,并且应该是一对多的并且尽可能多地反转一对一,但我想它也会起作用)

public function getRoles() 
    return $this->roles;


public function setRoles($role) 
    $this->roles = $role;

【讨论】:

我没听懂,但是你应该把洞实体传递给$user->setRole($theRole);,我会编辑我的答案 只需将其添加到您的实体中,例如 setRole($r)$this->roles = array($r);,实际实现取决于您的要求,但不应该很复杂。 我创建了 $user->setRoles(new \Trucking\MainBundle\Entity\UsersRole()); + I public function setRoles($role) $this->roles = array($role); ,但仍然没有..我正在考虑依赖.. 在创建此主题之前,我已经阅读了您的想法,但我不明白,我需要实现什么才能使这个简单的事情发生 您的实体应该包含一组属性以及 getter 和 setter。这就是信息被持久化并通过应用程序传递的方式。表单只是让用户在您的实体上设置值的一种简单方式,因此它们都是连接的。当您呈现表单时,它只会显示实体包含的数据,仅此而已。为什么不发布实体的完整代码?【参考方案2】:

ORM JOINS 出现问题。 id 到 role_id 我已将映射从一对一 双向 到一对一,单向与连接表。

完整代码:Users.php

<?php

namespace Trucking\MainBundle\Entity;

use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Security\Core\User\UserInterface;
/**
 * Trucking\MainBundle\Entity\Users
 *
 * @ORM\Table(name="Users")
 * @ORM\Entity
 */
class Users implements UserInterface

    /**
     * @var integer $id
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="IDENTITY")
     */
    protected $id;

    /**
     * @var string $password
     *
     * @ORM\Column(name="password", type="string", length=15)
     */
    protected $password;

    /**
     * @var string $username
     *
     * @ORM\Column(name="username", type="string", length=30)
     */
    protected $username;

    /**
     * @var string $description
     *
     * @ORM\Column(name="description", type="string", length=20)
     */
    protected $description;

    /**
     * @var string $permissions
     *
     * @ORM\Column(name="permissions", type="string", length=300)
     */
    protected $permissions;

    /**
     * @var integer $company_id
     *
     * @ORM\Column(name="company_id", type="integer")
     */    
    protected $company_id;

    /**
     * @var integer $role_id
     *
     * @ORM\Column(name="role_id", type="integer")
     */    
    protected $role_id;

    /**
     * @ORM\OneToOne(targetEntity="Company")
     * @ORM\JoinColumn( name="company_id", referencedColumnName="id" )
     */
    protected $companies;

    /**
     * @ORM\OneToOne(targetEntity="UsersRole")
     * @ORM\JoinColumn( name="role_id", referencedColumnName="id" )
     */
    protected $listRoles;

    public function __construct() 

    

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

    /**
     * Set password
     *
     * @param string $password
     * @return Users
     */
    public function setPassword($password)
    
        $this->password = sha1($password);

        return $this;
    

    /**
     * Get password
     *
     * @return string 
     */
    public function getPassword()
    
        return $this->password;
    

    /**
     * Set username
     *
     * @param string $username
     * @return Users
     */
    public function setUsername($username)
    
        $this->username = $username;

        return $this;
    

    /**
     * Get username
     *
     * @return string 
     */
    public function getUsername()
    
        return $this->username;
    

    /**
     * Set description
     *
     * @param string $description
     * @return Users
     */
    public function setDescription($description)
    
        $this->description = $description;

        return $this;
    

    /**
     * Get description
     *
     * @return string 
     */
    public function getDescription()
    
        return $this->description;
    

    /**
     * Set permissions
     *
     * @param string $permissions
     * @return Users
     */
    public function setPermissions($permissions)
    
        $this->permissions = $permissions;

        return $this;
    

    /**
     * Get permissions
     *
     * @return string 
     */
    public function getPermissions()
    
        return $this->permissions;
    

    /**
     * Set company_id
     *
     * @param Company $company_id
     * @return Users
     */
    public function setCompanyId($company_id)
    
        $this->company_id = $company_id;

        return $this;
    

    /**
     * Get company_id
     *
     * @return integer 
     */
    public function getCompanyId()
    
        return $this->company_id;
    

    public function equals(UserInterface $user) 
        return $this->getUsername() == $user->getUsername();
    

    public function eraseCredentials() 

    

    /**
     * Get roles
     *
     * @return String 
     */
    public function getRoles() 
        $roles = $this->getListRoles();
        return (array)$roles->getName();
    

    /**
     * Get roles
     *
     * @return \UsersRole 
     */
    public function getListRoles()
    
        return $this->listRoles;
    

    /**
     * Set roles
     *
     * @param \UsersRole
     * @return Users
     */
    public function setListRoles($roles)
    
        $this->listRoles = $roles;
        return $this;
    

    /**
     * Set role_id
     *
     * @param integer
     * @return Users
     */
    public function setRoleID($roleId) 
        $this->role_id = $roleId;
        return $this;
    

    public function getSalt() 

    

    /**
     * Get company
     *
     * @return Company
     */
    public function getCompanies()
    
        return $this->companies;
    

    /**
     * Set company
     *
     * @param Company $company
     * @return Users
     */
    public function setCompanies($company)
    
        $this->companies = $company;
        return $this;
    

UsersRole.php

<?php

namespace Trucking\MainBundle\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * USERS_ROLE
 *
 * @ORM\Table(name="USERS_ROLE")
 * @ORM\Entity
 */
class UsersRole

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

    /**
     * @var string
     *
     * @ORM\Column(name="name", type="string", length=30)
     */
    protected $name;

    /**
     * @var string
     *
     * @ORM\Column(name="description", type="string", length=200)
     */
    protected $description;

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

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

        return $this;
    

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

    /**
     * Set description
     *
     * @param string $description
     * @return USERS_ROLE
     */
    public function setDescription($description)
    
        $this->description = $description;

        return $this;
    

    /**
     * Get description
     *
     * @return string 
     */
    public function getDescription()
    
        return $this->description;
    

控制器没有改变

public function editAction($id) 
    $user = $this->getDoctrine()
            ->getEntityManager()
            ->getRepository('TruckingMainBundle:Users')
            ->find($id);

    if (!$user) 
        throw $this->createNotFoundException('Unable to find user id.');
    
    $form = $this->createForm(new \Trucking\AdminBundle\Form\UserType(), $user);
    $request = $this->getRequest();

    //save data
    if ($request->getMethod() == 'POST') 
        $form->bindRequest($request);
        if ($form->isValid()) 
            $em = $this->getDoctrine()->getEntityManager();
            $em->persist($user);
            $em->flush();
            return $this->redirect($this->generateUrl('tracking_admin_users'));
        
    
    return $this->render('TruckingAdminBundle:user:edit.html.twig', array(
                'id' => $id,
                'form' => $form->createView()
                    )
    );

UserType.php

<?php
namespace Trucking\AdminBundle\Form;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Validator\Constraints;

class UserType extends AbstractType 

    public function buildForm(FormBuilderInterface  $builder, array $options) 

     $builder
        ->add("username","text",array(
                   "label" => "Name",
                       'attr'   =>  array(
                           'class'   => 'input-xlarge',
                       ),
                    'constraints' => new Constraints\Length(array('min' => 3))
                   ))
        ->add("password","password",array(
                   "label" => "Password",
                       'attr'   =>  array(
                           'class'   => 'input-xlarge',
                       ),
                    'constraints' => new Constraints\Length(array('min' => 3))
                   ))
        ->add("listRoles","entity",array(
            'label' => 'Roles',
            'class'    => 'TruckingMainBundle:UsersRole' ,
            'property' => 'name'
        ))
        ->add("companies","entity",array(
            'label' => 'Companies',
            'class'    => 'TruckingMainBundle:Company' ,
            'property' => 'name'
        ))
        ->add("description","text",array(
           "label" => "Description",
               'attr'   =>  array(
                   'class'   => 'input-xlarge'
               ),
                'constraints' => new Constraints\NotBlank()
           ));
    

    public function getName()
    
        return 'trucking_adminbundle_usertype';
    

【讨论】:

以上是关于symfony2 选择的选项的主要内容,如果未能解决你的问题,请参考以下文章

Symfony2:使用 ajax 和验证更改选择

Symfony2 文件管理器 [关闭]

Symfony2 生成带有选项的实体字段

Symfony2 禁用选择

Symfony2 使用 EAV 返回值形成动态选择字段

Symfony2:没有空值的选择