Snickfire
Snickfire

Reputation: 512

How to validate empty input in Zend Framework 2

I'm doing a registration form in ZF2, but I don't get how to validate. Validation seems not working.

I'm adding the validators array, but it doesn't work anyways. I don't know how can I fix that.

This is my code of controller:

namespace Application\Controller;

use Zend\Mvc\Controller\AbstractActionController;
use Zend\View\Model\ViewModel;
use Application\Form\Formularios;
use Zend\Db\Adapter\Adapter;
use Application\Modelo\Entity\Usuarios;

class FormularioController extends AbstractActionController
{
   public $dbAdapter;
    public function indexAction()
    {
        return new ViewModel();
    }
    public function registroAction()
    {

        if($this->getRequest()->isPost())
        {
            $this->dbAdapter=$this->getServiceLocator()->get('Zend\Db\Adapter');
            $u=new Usuarios($this->dbAdapter);
            //echo "se recibió el post";exit;
            $data = $this->request->getPost();


            $u->addUsuario($data);
             return $this->redirect()->toUrl($this->getRequest()->getBaseUrl().'/application/formulario/registro/1');

        }else
        {
            //zona del formulario
                                 $form=new Formularios("form");

             $id = (int) $this->params()->fromRoute('id', 0);
             $valores=array
            (
                "titulo"=>"Registro de Usuario",
                "form"=>$form,
                'url'=>$this->getRequest()->getBaseUrl(),
                'id'=>$id
            );
            return new ViewModel($valores);
        }

    }

}

this is my form code with validator

class Formularios extends Form
{
    public function __construct($name = null)
     {
        parent::__construct($name);

        $this->add(array(
            'name' => 'name',
            'required'    => true,
         'allow_empty' => false,
            'options' => array(
                'label' => 'Nombre Completo',
            ),
            'attributes' => array(
                'type' => 'text',
                'class' => 'input'
            ),
            'filters' => [ ['name' => 'StringTrim'], ],

            'validators' => array(
             array(
            'name' => 'NotEmpty',
            'options' => array(
                'messages' => array(
                    \Zend\Validator\NotEmpty::IS_EMPTY => 'Ingrese Nombres.',
                ))))
        ));

         $this->add(array(
            'name' => 'lastname',
            'required' => true,
            'options' => array(
                'label' => 'Apellido',
            ),
            'attributes' => array(
                'type' => 'text',
                'class' => 'input'
            ),
            'validators' => array(
        array(
            'name' => 'NotEmpty',
            'options' => array(
                'messages' => array(
                    \Zend\Validator\NotEmpty::IS_EMPTY => 'Ingrese Apellidos.',
                ))))
        )); 

Thanks in advance

Upvotes: 1

Views: 1276

Answers (1)

Stanimir Dimitrov
Stanimir Dimitrov

Reputation: 1890

First problem.

$data = $this->request->getPost(); should be $data = $this->getRequest()->getPost();

Second problem is that you call your validators direclty when you build your form in the view, which is wrong. The right way to do is via an inputFilter. Now, there are many ways to to this, for example: with or without a factory called from your model or via the for class with a form element manager

I will show you the model way with a factory since it's easier for new comers.

namespace MyModule\Model;

use Zend\InputFilter\InputFilter;
use Zend\InputFilter\Factory as InputFactory;
use Zend\InputFilter\InputFilterAwareInterface;
use Zend\InputFilter\InputFilterInterface;

class MyModel implements InputFilterAwareInterface
{
    /**
     * @var null $_inputFilter inputFilter
     */
    private $_inputFilter = null;

   // some more code like exhnageArray get/set method

    public function setInputFilter(InputFilterInterface $inputFilter)
    {
        throw new \Exception("Not used");
    }

    public function getInputFilter()
    {
        if (!$this->inputFilter) {
            $inputFilter = new InputFilter();
            $factory = new InputFactory();
            $inputFilter->add(
                $factory->createInput([
                    'name'     => 'id',
                    'required' => false,
                    'filters'  => [
                        ['name' => 'Int'],
                    ],
                ])
            );
            $inputFilter->add(
                $factory->createInput([
                    "name"=>"title",
                    "required" => true,
                    'filters' => [
                        ['name' => 'StripTags'],
                        ['name' => 'StringTrim'],
                    ],
                    'validators' => [
                        ['name' => 'NotEmpty'],
                        [
                            'name'    => 'StringLength',
                            'options' => [
                                'encoding' => 'UTF-8',
                                'min' => 1,
                                'max' => 200,
                            ],
                        ],
                    ],
                ])
            );
            $inputFilter->add(
                $factory->createInput([
                    "name"=>"text",
                    "required" => true,
                    'filters' => [
                        ['name' => 'StripTags'],
                        ['name' => 'StringTrim'],
                    ],
                    'validators' => [
                        ['name' => 'NotEmpty'],
                        [
                            'name'    => 'StringLength',
                            'options' => [
                                'encoding' => 'UTF-8',
                                'min' => 1,
                            ],
                        ],
                    ],
                ])
            );
            $this->inputFilter = $inputFilter;
        }
        return $this->inputFilter;
    }

    }

Third proble. DO NOT EVER use serviceManager in controller. It's a really really really bad practice. Instead use a factory.

Upvotes: 1

Related Questions