在渲染小部件之前删除选择

时间:2014-07-29 12:52:00

标签: php symfony symfony-forms

我正在使用Fresh的DoctrineEnumBundle,我定义了这种类型:

namespace CommonBundle\DBAL\Types;

use Doctrine\DBAL\Platforms\AbstractPlatform;
use Fresh\Bundle\DoctrineEnumBundle\DBAL\Types\AbstractEnumType;

class AdminRoleType extends AbstractEnumType
{

    const ROLE_ADMIN = "ROLE_ADMIN";
    const ROLE_GERENTE = "ROLE_GERENTE";
    const ROLE_FISCAL = "ROLE_FISCAL";
    const ROLE_CENTRO_HIPICO = "ROLE_CENTRO_HIPICO";
    const ROLE_OPERADOR = "ROLE_OPERADOR";

    /**
     * @var string Name of this type
     */
    protected $name = 'AdminRoleType';

    /**
     * @var array Readable choices
     * @static
     */
    protected static $choices = [
        self::ROLE_ADMIN => 'Administrador',
        self::ROLE_GERENTE => 'Gerente',
        self::ROLE_FISCAL => 'Fiscal',
        self::ROLE_CENTRO_HIPICO => 'Centro Hípico',
        self::ROLE_OPERADOR => 'Operadora'
    ];

}

然后在我的表单类型中我有一个这样的字段:

....
->add('roleType', 'choice', array(
    'choices' => AdminRoleType::getChoices(),
    'required' => true,
    'label' => "User Type",
    'trim' => true
))
....

在一个视图中,我只需渲染ROLE_ADMINROLE_OPERADOR,但在另一个视图中,我需要渲染所有这些,我是如何做到的?

1 个答案:

答案 0 :(得分:0)

我为我的问题找到了解决方案,只需要添加尽可能多的方法来返回我需要的内容,请参阅下面的示例:

class RoleType extends AbstractEnumType
{
    const ROLE_ADMIN = "ROLE_ADMIN";
    const ROLE_GERENTE = "ROLE_GERENTE";
    const ROLE_FISCAL = "ROLE_FISCAL";
    const ROLE_CENTRO_HIPICO = "ROLE_CENTRO_HIPICO";
    const ROLE_OPERADOR = "ROLE_OPERADOR";

    /**
     * @var string Name of this type
     */
    protected $name = 'RoleType';

    /**
     * @var array Readable choices
     * @static
     */
    protected static $choices = [
        self::ROLE_ADMIN => 'Administrador',
        self::ROLE_GERENTE => 'Gerente',
        self::ROLE_FISCAL => 'Fiscal',
        self::ROLE_CENTRO_HIPICO => 'Centro Hípico',
        self::ROLE_OPERADOR => 'Operadora'
    ];

    public static function getFrontChoices()
    {
        return [
            self::ROLE_CENTRO_HIPICO => 'Centro Hípico',
            self::ROLE_OPERADOR => 'Operadora'
        ];
    }
}

然后在表单中,如果我只想显示ROLE_CENTRO_HIPICOROLE_OPERADOR而不是致电getChoices(),我会致电getFrontChoices()

....
->add('roleType', 'choice', array(
    'choices' => AdminRoleType::getFrontChoices(),
    'required' => true,
    'label' => "User Type",
    'trim' => true
))
....

全部