2013-11-20 151 views
2

我使用这个代码创建Symfony2的形式:Symfony2的表单验证单选按钮

$builder 
     ->add('layout_type', 'choice', array(
       'choices' => array(0 => 'Small layout', 1 => 'Big layout'), 
       'expanded' => true, 
       'disabled' => $disabled 
      )) 

.... ))

我的问题是与单选按钮验证(layout_type,选择) 。

当我没有选择任何单选按钮并提交表单时,数据没有插入到数据库中。 这是正确的,因为单选按钮是强制字段,但是当表单重新加载时,我没有关于单选按钮错误的消息。我正确地获取所有其他字段的错误。

嫩枝我使用:

<table width="1000"> 
     <tr> 
      <td class="label">{{ form_label(form.layout_type, 'LAYOUT_TYPE') }}</td> 
      <td class="widget">{{ form_widget(form.layout_type) }} {{ form_errors(form.layout_type) }}</td> 
     </tr> 
     ... 

而对于验证我使用注释:

/** 
* @var Integer 
* @Assert\NotBlank(message="NOT_EMPTY") 
*/ 
protected $layoutType; 

我只有与$ layoutType单选按钮的错误消息的问题 是否有人知道有什么可一个问题。 THX

回答

0
try this: 

'choices' => array(0 => 'Small layout', 1 => 'Big layout'), 
        'expanded' => true, 
        'disabled' => $disabled, 
        'constraints' => new Assert\NotBlank(array('message' => 'YOUR_MESSAGE')) 
+1

是其工作正常。谢谢。但我仍不明白为什么注释不起作用。 – kukipei

0

你有没有实际的实体之前加入

use Symfony\Component\Validator\Constraints as Assert; 

class entity { 

    /** 
    * @Assert\NotBlank() 
    */ 
    public $layoutType; 
    ........ 
} 
+0

是的,我做到了。对于其他字段错误信息正常工作。 – kukipei

+0

添加断言约束后,您是否重新生成实体? – satdev86

+0

是的,我也那样做过。不起作用 – kukipei