如何正确设置表单验证器渲染


How to properly setup form-validator-render

我想设置一个表单验证器渲染控制器:

形式:

<?php
namespace Application'Form;
use Zend'Form'Form;
class AjouterCompteForm extends Form
{
    public function __construct()
    {
        parent::__construct();
        $this->add(array(
            'name' => 'role',
            'attributes' => array(
                'label' => 'Rôle',
                'class' => 'form-control',
            ),
        ));
        $this->add(array(
            'name' => 'ajouter',
            'attributes' => array(
                'type' => 'submit',
                'label' => 'Ajouter',
                'class' => 'btn btn-primary',
            ),
        ));        
    }
}
?>

验证器:

<?php
namespace Application'Validator;
use Zend'Db'ResultSet'Row;
use Zend'InputFilter'InputFilter;
use Zend'InputFilter'Factory as InputFactory;
use Zend'InputFilter'InputFilterAwareInterface;
use Zend'InputFilter'InputFilterInterface;
class AjouterCompteValidator extends Row implements InputFilterAwareInterface
{    
    protected $inputFilter;
    public function setInputFilter(InputFilterInterface $inputFilter){
        throw new 'Exception("Non utilisée");
    }
    public function getInputFilter()
    {
        if (!$this->inputFilter) {
            $inputFilter = new InputFilter();
            $factory = new InputFactory();
            $inputFilter->add(
                'name' => 'role',
                'required' => true                
            );
            $this->inputFilter = $inputFilter;
        }
        return $this->inputFilter;
    }
}
?>

渲染:

<?php
$form = $this->form;
$form->setAttribute('action', $this->url('compte', array('action' => 'ajouter')));
echo $this->form()->openTag($form);
?>
<div class="form-group">
    <?php 
        echo $this->formSelect($form->get('role')); 
        echo $this->formElementErrors($form->get('role'));
    ?>
</div>
<?php
    echo $this->formButton($form->get('submit'));
    echo $this->formElementErrors($form->get('submit'));
?>

这样做,我得到以下错误消息:

Zend'Form'View'Helper'FormSelect::render要求元素是'Form'Element'Select

请问如何解决这个问题?

在表单构造函数中设置的所有元素都应该有一个类型:

public function __construct()
{
    parent::__construct();
    $this->add(array(
        'name' => 'role',
        'type' => 'select', // <- add this line
        'options' => array(
            'label' => 'Rôle',
        ),
        'attributes' => array(
            'class' => 'form-control',
        ),
    ));
    $this->add(array(
        'name' => 'ajouter',
        'type' => 'submit', // <- add this line
        'options' => array(
            'label' => 'Ajouter',
        ),
        'attributes' => array(
            'type' => 'submit', // <- this line is unnecessary
            'class' => 'btn btn-primary',
        ),
    ));        
}