【问题标题】:The Choice constraint expects a valid callbackChoice 约束需要一个有效的回调
【发布时间】:2012-07-21 15:09:39
【问题描述】:

我将 Symfony2 更新到 2.1,当我尝试提交表单时出现错误:

Choice 约束需要一个有效的回调

表单类型类的源代码:

$builder->add('type', 'choice', 
                    array(
                        'expanded' => true, 
                        'multiple' => false,
                        'choice_list' => new TypeChoices(),
                        'required' => true,
                    )
                  )

TypeChoices 类:

class TypeChoices implements ChoiceListInterface {

    public static $choices = array(
        'full-time' => 'Full time', 
        'part-time' => 'Part time', 
        'freelance'  => 'Freelance',
    );

    public static function getChoiceNameByValue($value)
    {
        return self::$choices[$value];
    }

    public function getChoices() 
    {   
        return self::$choices;  
    }

    public static function getTypeChoicesKeys() 
    {
        return array_keys(self::$choices);
    }

    public static function getPreferredChoiceKey()
    {
        return 'full-time';
    }
}

有人可以给我任何建议吗?

【问题讨论】:

标签: forms symfony-2.1


【解决方案1】:

也许你可以尝试扩展 SimpleChoiceList 类,这样:

选择列表代码:

class TypeChoices extends SimpleChoiceList
{
    public static $choices = array(
        'full-time' => 'Full time', 
        'part-time' => 'Part time', 
        'freelance'  => 'Freelance',
    );

    /**
     * Constructor.
     *
     * @param array $preferredChoices Preffered choices in the list.
     */
    public function __construct(array $preferredChoices = array()) // PASS MORE ARGUMENT IF NEEDED
    {
        parent::__construct(
            static::$choices,
            $preferredChoices
        );
    }
}

表格类型代码:

->add('type', 'choice', array(
    'choice_list' => new TypeChoices(),
    ...
))

【讨论】:

    猜你喜欢
    • 2021-06-08
    • 2021-02-10
    • 2018-12-22
    • 1970-01-01
    • 2023-03-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-14
    相关资源
    最近更新 更多