Symfony2选择静态列表

时间:2014-07-22 20:05:44

标签: symfony doctrine formbuilder

我想使用带有预定义值的选择框。我有一个Task实体:

namespace xx\xxx\Entity;

use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
/**
 * Task
 *
 * @ORM\Table()
 * @ORM\Entity(repositoryClass="xx\xxx\Entity\TaskRepository")
 */
class Task
{

////

/**
 * @Assert\Choice(choices = {"MONTHLY", "WEEKLY"}, message = "Select frequency")
 * @ORM\Column(name="frequency", type="text")
 */
private $frequency;    
}

使用TaskType时:

$builder->add('frequency');

显示正确验证的输入 - 仅允许WEEKLY和MONTHLY值。但我想使用选择框。我试过了:

   $builder->add('frequency', 'collection', array(
           'type' => 'choice',
           'options' => array(
               'choices' => array(
                   'MONTHLY' => 'Monthly',
                   'WEEKLY' => 'Weekly',
               )
           )
       )
   )

或:

   $builder->add('frequency', 'collection', array(
           'type' => 'choice',
       )
   )

但两种方式我只得到一个没有选择框的标签。我做错了什么?也许有更好的方法?

1 个答案:

答案 0 :(得分:3)

尝试这样做:

$builder->add('frequency', 'choice', array(
    'choices'   => array(
        'MONTHLY'   => 'Monthly',
        'WEEKLY'    => 'Weekly'
    )
));

此处choice字段类型的更多内容 - http://symfony.com/doc/current/reference/forms/types/choice.html