2

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

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

表单类型类的源代码:

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

类型选择类:

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';
    }
}

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

4

1 回答 1

0

也许您可以尝试以这种方式扩展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(),
    ...
))
于 2012-07-24T14:11:30.857 回答