如何正确设置form-validator-render

时间:2014-07-14 11:55:09

标签: php forms validation zend-framework

我试图以这种方式设置form-validator-render-controller:

形式:

<?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要求元素为   类型为Zend \ Form \ Element \ Select

如何解决这个问题,好吗?

1 个答案:

答案 0 :(得分:0)

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

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