【问题标题】:How to set the default selected value for a Doctrine ObjectRadio element如何为 Doctrine ObjectRadio 元素设置默认选定值
【发布时间】:2014-08-04 23:24:48
【问题描述】:

我有一个简单的用户注册表单,用户可以在其中选择自己的用户类型。用户类型映射到角色。这是 zf2 应用程序的一部分,使用了教义 2 模块。

我的用户字段集的 init() 方法的相关部分如下所示: 公共函数初始化() { // ... 其他字段定义 ...

    $roleRadio = new ObjectRadio('role');
    $roleRadio->setLabel('What type of user are you?')
              ->setOptions(
                    array(
                        'object_manager' => $this->objectManager,
                        'target_class'   => 'MyUser\Entity\Role',
                        'property'       => 'roleId',
                        'is_method'      => true,
                        'find_method'    => array(
                            'name'   => 'findBy',
                            'params' => array(
                                'criteria' => array('userselectable' => true),
                                'orderBy'  => array('displayorder' => 'ASC'),
                            ),
                        ),
                    )
    );

    $this->add($roleRadio);

    // ... more stuff ...
}

我正在为这个元素使用 Doctrine 的 ObjectRadio 类来自动填充值选项。有没有办法设置默认选择值? 我知道我可以这样做:

$form->get('user')->get('role')->setValue(3);

但我不想硬编码,我也不想把那种逻辑放在我的控制器中。

有什么建议吗?

【问题讨论】:

    标签: doctrine-orm zend-framework2


    【解决方案1】:

    我不知道“我不想硬编码”是什么意思,但是您可以按照您在控制器中所说的那样做,或者您可以在表单定义中通过将属性设置为以下:

    $roleRadio->setAttributes(array('value' => 3));
    

    【讨论】:

    • 我所说的硬编码是指默认选项的id。如果角色的 id 发生变化,我不希望它中断,因为它只是一个自动增量列。
    • 如果您有角色对象,那么您可以使用setValue($roleObject) 设置ObjectRadio 当前值,并且您可以将唯一的role_code 列添加到角色表并通过其代码选择角色...这将删除对 ID 的依赖
    • 是的,我现在就是这样解决的。我为用户模块“default_role”添加了一个配置选项,它指的是唯一的角色名称。在 UserService 中,我现在有一个返回角色实体的 getDefaultRole()。我在创建表单时将其分配给表单。感谢您的参与。
    猜你喜欢
    • 2015-07-23
    • 1970-01-01
    • 1970-01-01
    • 2021-03-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多