2012-02-23 67 views
3

我有两个实体文件,一个是user.php,另一个是usertype.php。现在我想显示一个3字段的用户名,密码和用户类型的登录表单。 usertype将是一个将从usertype表中获取数据的选择。这里要说的是我里面写user.php的创建多对一领域usertype_id代码以Symfony2形式显示ManyToOne字段?

/** 
* @ORM\ManyToOne(targetEntity="Usertype") 
*/ 
protected $usertype; 

下面是我的表单生成代码

class LoginForm extends AbstractType 
{ 
    public function buildForm(FormBuilder $builder, array $options) 
    { 
     $builder->add('login', 'text', array('label' => 'Username',)); 
     $builder->add('password'); 
    } 
} 

现在我需要多一个字段添加到我的表单生成器这将是一个usertype表的选择。

回答

9
... 
use Acme\YourBundle\Entity\Usertype; 

class LoginForm extends AbstractType { 

    public function buildForm(FormBuilder $builder, array $options) 
    { 
     $builder->add('usertype', 'entity', 
      array(
       'class' => 'AcmeYourBundle:Usertype' 
       'label' => 'User Type', 
      ) 
     ); 
    } 
} 

你可以阅读更多的信息有关the entity field type至极会给你提供这种类型的字段的选项。

不要忘了添加一个__toString()方法到您的模型告诉表单生成器显示什么。

namespace Acme\YourBundle\Entity; 

use Doctrine\ORM\Mapping as ORM; 

class Usertype 
{ 
    public function __toString() 
    { 
     return $this->getName(); 
    } 
} 
+0

到“实体字段类型”的链接已过期。更新后的链接是http://symfony.com/doc/current/reference/forms/types/entity.html – luchaninov 2015-10-22 12:01:07

+0

@how它的更新谢谢。 – rayfranco 2015-10-26 17:41:45

2

还有其他的方法来做到这一点,但你可以试试这个:

$builder->add('usertype', 'entity', 
    array(
     'class' => 'YourBundle:UserType 
     'required' => true, // Choose if it's required or not 
     'empty_value' => 'User type', // Remove this line if you don't want empty values 
     'label' => 'Type', // You can put a label here or remove this line 
    ) 
); 

我希望它帮助!

+0

这不起作用 – ScoRpion 2012-02-23 06:27:17

+0

@Showket如果您勾画了*为什么*它不适用于您... – richsage 2012-02-23 08:32:36

-1

http://symfony.com/doc/2.0/reference/forms/types/entity.html

property¶

类型:字符串

这是应用于显示实体在HTML文本元素的属性。如果留空,实体对象将被转换为一个字符串,因此必须有一个__toString()方法。

+0

您能否做更多的事情而不仅仅是引用文档?这可能会让你的回答更清晰。 – 2014-07-13 01:24:25