【问题标题】:Display ManyToOne field in Symfony2 forms?在 Symfony2 表单中显示 ManyToOne 字段?
【发布时间】:2012-02-23 05:03:38
【问题描述】:

我有两个实体文件,一个是 user.php,另一个是 usertype.php。现在我想显示一个包含 3 个字段的登录表单,即用户名、密码和用户类型。 usertype 将是一个从 usertype 表中获取数据的选择。这是我在 user.php 中编写的代码,用于为 usertype_id 创建一个多单字段

/**
* @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');
    }
}

现在我需要在表单构建器中再添加一个字段,作为用户类型表的选择。

【问题讨论】:

    标签: symfony


    【解决方案1】:
    ...
    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();
        }
    }
    

    【讨论】:

    【解决方案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
        )
    );
    

    希望对你有帮助!

    【讨论】:

      【解决方案3】:

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

      属性¶

      类型:字符串

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

      【讨论】:

      • 您能做的不仅仅是简单地引用文档吗?这可能会让你的答案更清楚一点。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-04-10
      相关资源
      最近更新 更多