Solved thread

This post is marked as solved. If you think the information contained on this thread must be part of the official documentation, please contribute submitting a pull request to its repository.

Best way to validate a form

Hello,

ok there are a lot of examples to validate a form, but which one is the best way to practise?

It confuses me a little bit.

I created the indexAction Controller for the site of my form. And now, have i got to create a new class for the validation? And how can i do it? How does the form know the validation class?

I am also using volt and of course phalcon 2.0.

Thx for your ideas.

Rgds

Stefan



4.0k
edited Jul '15

Honestly,

I've found the easiest way is to create a form that extends \Phalcon\Forms\Form:

Example of a very simple login form. You can add extra security as you see fit but this is just an example:

<?php
/**
* Login Form
* File: /my/app/path/library/App/Forms/LoginForm.php
*/

    namespace App\Forms;

    use Phalcon\Forms\Form,
    Phalcon\Forms\Element\Text,
    Phalcon\Forms\Element\Password;

    use Phalcon\Validation\Validator\Identical;
    use Phalcon\Validation\Validator\PresenceOf;

    class LoginForm extends Form {

        public function initialize()
        {
            $this->setEntity($this);

            $email_address = new Text("email_address");
            $email_address->addValidator(new PresenceOf(array(
                'message' => 'Email Address is required'
            )));
            $email_address->setAttribute('class','form-control');

            $password = new Password('password');
            $password->setAttribute('class','form-control');
            $password->addValidator(new PresenceOf(array(
                'message' => 'Password is required'
            )));

            $this->add($email_address);
            $this->add($password);
        }
    }

Then in your controller:

    <?php
/**
* Auth Controller
* File: /my/app/path/apps/frontend/controllers/AuthController.php
*/

    namespace App\Frontend\Controllers;

    use App\Forms\LoginForm;

    class AuthController extends ControllerBase
    {

        public function loginAction()
        {

            $form = new LoginForm();

            // Check to see if this is a POST request
            if($this->request->isPost())
            {

                // Validate the form data posted
                if(!$form->isValid($this->request->getPost())){

                    // If the form failed validation, add the errors to the flash error message.
                    foreach($form->getMessages() as $message){
                        $this->flash->error($message->getMessage());
                    }

                } else {

                    // Form was validated successfully. Lets try to login
                    $email    = $this->request->getPost('email_address', 'email');
                    $password = $this->request->getPost('password');

                    $login = \App\Users::authenticate($email, $password);

                    if ($login) {
                        // Success! Set your session data here

                    } else {
                        // Login Failed!
                        $this->flash->error('Invalid Login Details');

                    }
                }

            }

            // Send the form to the view.
            $this->view->form = $form;
        }

    }

And for your view:

<!--
Login View
File: /my/app/path/apps/frontend/views/auth/login.volt
-->

<form method="post" action="/post/url/here">
<label for="email_address">Email Address: </label>
{{ form.render('email_address') }}
<label for="password">Password: </label>
{{ form.render('password') }}
</form>


14.5k

Good morning Steven,

thx i will try it, now it is clearer for me :-)

Is the action url, the url to AuthController.php?

Rgds

Stefan



4.0k

Hi Stefan,

Yes, the action url is the url to the AuthController.php in my case I setup my route like this:

$router->add('/login',[
    'namespace' => 'App\Frontend\Controllers',
    'module' => 'frontend',
    'controller' => 'auth',
    'action' => 'login',
])->setName('login');


14.5k

Hi Steven,

it is chaos in my head :-))) But i never give up!!!

I tested your way yesterday, but i've got an error. Undefinied variable form and render() not found. The form is also not displayed.

Rgds

Stefan



9.6k
Accepted
answer

You need to setup autoloader, to get the namespace :-)

Let's say that LoginForm is in the app/form/ folder then you have to do this in the config/loader.php file:

$loader->registerNamespaces(
  array(
      'App\Frontend\Controllers'  => __DIR__.'/../forms/'
  )
)->register();

You can change App\Frontend\Controllers to what ever you like to use, when you call the class namepsace

Here the namespace is "namespace App\Frontend\Controllers;" after that you can use the form class, becuase it now included in the file :-)