We have moved our forum to GitHub Discussions. For questions about Phalcon v3/v4/v5 you can visit here and for Phalcon v6 here.

Non-model validation isnt working ...

Hi,

i started my first project in phalcon (1.3.0) and i must say that I am really fascinated of it ! I worked for the last 2 years with CakePHP but Phalcon is absolutely outstanding.

So, my problem: I have a a form which i want to validate by extending the Form class. The form is shown correctly, but the validation failed of PresenceOf, InclusionIn, Email, StringLength and Confirmation. I tried everything the last 3 days, but could't fix this problem.

<?php

use Phalcon\Forms\Form;
use Phalcon\Forms\Element\Text;
use Phalcon\Forms\Element\Select;
use Phalcon\Forms\Element\Password;
use Phalcon\Forms\Element\Submit;

use Phalcon\Validation;
use Phalcon\Validation\Validator\PresenceOf;
use Phalcon\Validation\Validator\InclusionIn;
use Phalcon\Validation\Validator\Email;
use Phalcon\Validation\Validator\StringLength;
use Phalcon\Validation\Validator\Confirmation;

class KundenRegistrationForm extends Form {

    public function initialize()
    {

        ### Adresses[anrede]
        $anrede = new Select ("anrede" , array("Frau" => "Frau" , "Mann" => "Mann") , array(
            'using' =>  array(
                'id',
                'name' 
            ),
            'name'  => 'Adresses[anrede]',
            'useEmpty'      => true,
            'emptyText'     => 'Bitte auswählen...',
            'emptyValue'    => '',
            'class'     =>  'formular',
            'required' =>   'required'
        ));

        $anrede->setDefault("Frau"); ## SELECTED VALUE

        ##############################
        ##############################
        ##### THIS IS NOT WORKING #####
        ### Allways shows the message ! ###
        ##############################
        $anrede->addValidators(array(
            new InclusionIn(
                array(
                    'field'    => 'anrede',
                    'domain' => array("Frau", "Herr"),
                    'message' => "Die Auswahl Ihrer ANREDE war falsch."
                )
            ) 
        )); 

        $this->add($anrede);

        #### Adresses[vorname]
        $vorname = new Text('vorname', array(
            'placeholder' => 'Vorname',
            'class' => 'formular',
            'required'  =>  'required',
            'name'  =>  'Adresses[vorname]'
        ));

        $vorname->setDefault("mein nam");

        ##############################
        ##############################
        ##### THIS IS NOT WORKING #####
        ### Allways shows the message ! ###
        ##############################
        $vorname->addValidators(array(
            new PresenceOf(array(
                'message' => 'Vorname fehlt'
            ))
        ));

        $vorname->addFilter('string');

        $this->add($vorname);

        #### User[email]
        $email = new Text('email',array(
            'placeholder' => 'Email-Adresse',
            'class' => 'formular',
            'required'  =>  'required',
            'name'  =>  'User[email]'
        ));

        //$email->setDefault("[email protected]");

        ##################################
        ###################################
        ##### THIS IS NOT WORKING ###########
        ### Allways shows the BOTH message ! ###
        ###################################
        $email->addValidators(array(
             new PresenceOf(array(
                'message' => 'Ihre Email fehlt'
            )),
            new Email(array(
                'message' => 'Ihre Email-Adresse ist falsch'
            ))
        ));

        $this->add($email);

        ### Adresses[telefon]
        $telefon = new Text( "telefon" , array(
            'placeholder' => '0309282733',
            'class' => 'formular',
            'required'  =>  'required',
            'name'  =>  'Adresses[telefon]'
        ));

        $telefon->setDefault("4567890");

//        $telefon->addValidators(array(
//            new Numericality(
//                array(
//                    'field'    => 'telefon'
//                )
//            )  
//        ));

        $this->add($telefon);

        #### User[passwort]
        $passwort = new Password("passwort", array(
            'class' => 'formular',
            'required' => 'required',
            'name'  =>  'User[passwort]'
        ));
        $passwort->setDefault("asdfsafd");

         ##############################
        ##############################
        ##### THIS IS NOT WORKING #####
        ### Allways shows the message ! ###
        ##############################
        $passwort->addValidators(array(
            new PresenceOf(array(
                'message' => 'Bitte tragen Sie ein Passwort ein.'
            )),
            new StringLength(array(
                'min' => 6,
                'messageMinimum' => 'Das Passwort muss mindestens aus 6 Zeichen bestehen.'
            )),
            new Confirmation(array(
                'message' => 'Die Passwörter stimmen nicht überein.',
                'with' => 'passwort2'
            ))
        ));

        $this->add($passwort);

         #### User[passwort2]
        $passwort2 = new Password("passwort2", array(
            'class' => 'formular',
            'required' => 'required',
            'name'  =>  'User[passwort2]'
        ));
        $passwort2->setDefault("asddfsafd");

         ##############################
        ##############################
        ##### THIS IS NOT WORKING #####
        ### Allways shows the message ! ###
        ##############################
        $passwort2->addValidators(array(
            new PresenceOf(array(
                'message' => 'Bitte wiederholen Sie Ihr Passwort'
            ))
        ));

        $this->add($passwort2);
    }

}

in My Controller:

<?php
use Phalcon\Mvc\Model\Criteria;
use Phalcon\Paginator\Adapter\Model as Paginator;
use Phalcon\Mvc\View;
use Phalcon\Mvc\Controller;

class UsersController extends ControllerBase
{
    public function registerAction()
    {
            $test  = new KundenRegistrationForm();

             if(!$test->isValid($this->request->getPost("Adresses"))){
               foreach ($test->getMessages() as $message) {

                   echo "<br />Adresses - Message: ", $message->getMessage();
                    echo "<br />Field: ", $message->getField();
                    echo "<br />Type: ", $message->getType();
                    echo "<br />";
                }

            }
            if(!$test->isValid($this->request->getPost("User"))){
               foreach ($test->getMessages() as $message) {
                    echo "<br />Users -- Message: ", $message->getMessage();
                    echo "<br />Field: ", $message->getField();
                    echo "<br />Type: ", $message->getType();
                    echo "<br />";
                }

            }

            $this->view->form = $test;
        }

}

What i am doing wrong?

I would be very grateful for any help.

I also compared my code with Pahlcon Vakuro , but without success to get it work. :-(



26.3k
edited Aug '14

Change your controller to this:


<?php
use Phalcon\Mvc\Model\Criteria;
use Phalcon\Paginator\Adapter\Model as Paginator;
use Phalcon\Mvc\View;
use Phalcon\Mvc\Controller;

class UsersController extends ControllerBase
{
    public function registerAction()
    {
            $test  = new KundenRegistrationForm();

             if(!$test->isValid($this->request->getPost())){
               foreach ($test->getMessages() as $message) {

                   echo "<br />Adresses - Message: ", $message->getMessage();
                    echo "<br />Field: ", $message->getField();
                    echo "<br />Type: ", $message->getType();
                    echo "<br />";
                }

            }

            $this->view->form = $test;
        }

}

So you need to delete the second if and in the first if you need make a change:

from getPost("Adresses") to getPost()

Did it help?



26.3k

So what you are doing wrong is:

  1. You pass to isValid() method only a value of one field. You should pass the whole $_POST array.
  2. I think that each time you invoke isValid() method the messages are deleted / overwritten.
edited Aug '14

At first, thanks for your help till now... but .... my complete POST ARRAY looks like this:

Array
(
    [User] => Array
        (
            [email] => [email protected]
            [passwort] => asdfsafd
            [passwort2] => asddfsafd
        )

    [llVgaMOG3XP6VEQB] => 8a0ed26fcbb87e3eb3d2eeac0cce4e26
    [Adresses] => Array
        (
            [anrede] => Frau
            [titel] => Dipl. Ing.
            [vorname] => mein nam
            [nachname] => nachname
            [telefon] => 4567890
            [mobilfunk] => 0172123456789
            [fax] => 030987654567
            [firma_name] => Meine GmbH
            [umsatzsteuernummer] => DE6789 s2342342
            [strasse] => neue Strassse
            [hausnummer] => 99a
            [postleitzahl] => 89264
            [stadt] => Ulm
        )

)

Thats the reason why I wrote: !$test->isValid($this->request->getPost("User"))

because my form looks like this (part of it):

<form action="/xxxx/login" data-abide="data-abide" method="post">    

<select name="Adresses[anrede]" >
    <option value="">Bitte auswählen...</option>
    <option value="Frau" selected="selected">Frau</option>
    <option value="Mann">Mann</option>
</select>

<!-- Email //-->
<input type="text"  name="User[email]" >

<!-- vorname //-->
<input type="text"  name="User[vorname]" >

<!-- Passwort //-->
<input type="password" value="asdfsafd" name="User[passwort]" >

<!-- Passwort2 //-->
<input type="password" value="asddfsafd" name="User[passwort2]" >

<input type="submit" class="small button radius" value="Anmelden">

</form>

Also I tried to pass the POST without my Array-structure, but I had the same issues... :-8

Above my From in View I see that all validation-criterias are faild by getting my messages:

Adresses - Message: Ihre Email fehlt
Field: email
Type: PresenceOf

Adresses - Message: Ihre Email-Adresse ist falsch
Field: email
Type: Email

Adresses - Message: Bitte tragen Sie ein Passwort ein.
Field: passwort
Type: PresenceOf

Adresses - Message: Das Passwort muss mindestens aus 6 Zeichen bestehen.
Field: passwort
Type: TooShort

Adresses - Message: Bitte wiederholen Sie Ihr Passwort
Field: passwort2
Type: PresenceOf

Users -- Message: Die Auswahl Ihrer ANREDE war falsch.
Field: anrede
Type: InclusionIn

Users -- Message: Vorname fehlt
Field: vorname
Type: PresenceOf


26.3k
Accepted
answer

OK, this will solve the issue:


public function registerAction() {

    $test  = new KundenRegistrationForm();

    // this is a new code
    $data = array_merge(
        $this->request->getPost("Adresses"),
        $this->request->getPost("User")
    );

     if(!$test->isValid($data)){ //little change
       foreach ($test->getMessages() as $message) {

           echo "<br />Adresses - Message: ", $message->getMessage();
            echo "<br />Field: ", $message->getField();
            echo "<br />Type: ", $message->getType();
            echo "<br />";
        }

    }

    //second if deleted

    $this->view->form = $test;

}


26.3k
edited Aug '14

I am sorry that have not looked carefully at the code the first time but I have spotted the issue with isValid() (invoked two times) and was focused on that.

So what was going on was:

  1. You have invoked isValid() method first time. You provided the method with fields: anrede, vorname, telefon.
  2. Phalcon is generating messages for these fields: email, passwort, passwort2.
  3. You print messages from point 2
  4. You are invoking isValid() method second time. Phalcon is deleteing all messages. You provided diffirent set of fields (email, passwort, passwort2)
  5. Phalcon is generating messages only for this fields: anrede, vorname, telefon

WOW !!!!

It fixed my problem by merging the Arrays !!!

$data = array_merge(
        $this->request->getPost("Adresses"),
        $this->request->getPost("User")
    );

After that, everything is working like a charm.

I am really thankful for your help !!