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

display form error messages underneath the input fields

Hi everyone. Is there a way to display error messages underneath the input fields of a form if a field didn't pass validation? Can I somehow process form in the same action (User/index in my case) that the form is displayed and then send those error messages to view? What I have is : index.voit:

<div class="loginForm">
    <form action=<?= $form->getAction(); ?> method="POST">
    <label for="username">Username: </label>
    <?= $form->render('username'); ?>
        <br/>
    <label for="password">Password: </label>
    <?= $form->render('password'); ?>
    <br>
    <?= $form->render('login'); ?>
    </form>
</div>

LoginForm.php:

<?php
use Phalcon\Forms\Form,
Phalcon\Forms\Element\Text,
Phalcon\Forms\Element\Password,
Phalcon\Forms\Element\Submit,
Phalcon\Validation\Validator\PresenceOf,
Phalcon\Validation\Validator\StringLength;

class LoginForm extends Form {

public function initialize()
{
    $this->setAction('login');
    $username = new Text('username');
    $username->addValidator(new PresenceOf(array (
        'message' => 'Can\'t be empty'
    )));

    $password = new Password('password');
    $password->addValidator(new PresenceOf(array (
        'message' => 'Can\'t be empty'
    )));

    $submit = new Submit('login', array('value' => 'Login'));

    $this->add($username);      
    $this->add($password);
    $this->add($submit);
}
}

And UserController.php:

<?php

class UserController extends \Phalcon\Mvc\Controller
{
/**
 * login form
 * @var LoginForm
 */
private $_loginForm;
public function initialize()
{
    $this->_loginForm = new LoginForm();
}

public function indexAction()
{
    $this->view->setVar('form', $this->_loginForm);
}
public function loginAction()
{   
    if($this->request->isPost()) {

        if (!$this->_loginForm->isValid($this->request->getPost())) {
            foreach ($this->_loginForm->getMessages() as $message) {
                echo $message. '<br />';
            }
        }
        print_r($this->request->getPost());
    }
}

}


16.2k

Since you are POSTing to a different action you have a couple different ways to go about it:

  1. In your loginAction set the form to view with view->setVar, and under your field, use form->getMessagesFor('username'). You can either manually pick the index view to render again, or render a different view like a separate login page.
  2. Somehow store the messages in session, and redirect back to indexAction. Check if the form messages your set in session exists and render them to view.
  3. POST to indexAction instead and handle loginForm validation there.

But to render messages for a specific field, all you have to do is loop through $form->getMessagesFor('username'), just like you did in your loginAction