2015-11-24 95 views
2

我想为使用条款制作一个chekbox。我发现一个有趣的解决方案,由webcoder提供How to validate a checkbox in ZF2zf2复选框由formInput渲染失败

这种情况是,我有一个困难的HTML结构,这就是为什么我既不能使用formRow也不能使用formCollection来呈现。我试图用下面的办法来代替:

$agreement = $form->get('agreement'); 
echo $this->formInput($agreement); 
echo $this->formElementErrors($agreement); 

而且我收到了空值:

<input type="checkbox" name="agreement" class="checkbox" value=""> 

我也试图添加隐藏字段,但我的尝试也失败:

$agreement = $form->get('agreement'); 
echo $this->formHidden($agreement); 
echo $this->formInput($agreement); 
echo $this->formElementErrors($agreement); 

的HTML是:

<input type="hidden" name="agreement" class="checkbox" value=""> 
<input type="checkbox" name="agreement" class="checkbox" value=""> 

因此我收到有关“值是必需的,不能为空”的错误

可能有人可以给我一个提示如何正确呈现复选框在我的情况?我输入过滤的

代码:

<?php 
namespace Auth\Form; 

use Zend\InputFilter\InputFilter; 
use Zend\Validator\Digits; 

class UserFormFilter extends InputFilter { 

    public function __construct() { 

     $this->add(array(
      'name' => 'agreement', 
      'validators' => array(
       array(
        'name' => 'Digits', 
        'break_chain_on_failure' => true, 
        'options' => array(
         'messages' => array (
          Digits::NOT_DIGITS => 'You must agree to the terms of use.', 
         ) 
        ), 
       ), 

      ), 
     )); 
    } 
} 
?> 
+0

你可以添加你的InputFilter的代码吗? – StoryTeller

+0

补充说,我使用了一个,在链接中提供http://stackoverflow.com/questions/13459581/how-to-validate-a-checkbox-in-zf2 – Sabine

+1

可能值得阅读关于formCheckbox使用的文档'视图帮助和使用,而不是'formInput' - > http://framework.zend.com/manual/current/en/modules/zend.form.elements.html#checkbox – Crisp

回答

0

看看这个吧。

$this->add(array(
     'type' => 'Zend\Form\Element\Checkbox', 
     'name' => 'agreeterms', 
     'options' => array(
      'label' => 'I agree to all terms and conditions', 
      'use_hidden_element' => true, 
      'checked_value' => 1, 
      'unchecked_value' => 'no' 
     ), 
     'attributes' => array(//the difference is here 
      'value' => 'yes' 
     ) 
    )); 

如果添加属性阵列它应该工作。