How to show error messages in View using Phalcon

904 Views Asked by At

I need to show the error messages in View

Here is my code:

This is my form code:

public function initialize() {

        $name = new Text('name', array(
            'class' => 'form-control',
            "placeholder" => "Type your name"
        ));

        $name->addValidators(array(
            new PresenceOf(array(
                'message' => 'Please enter your username.',
            )),
        ));

        $this->add($name);

    }

Here is my html code:

<form method="post" action="user">

    <p>
        <label>
            Name
        </label>
        <?php echo $userForm->render("name"); ?>
    </p>


    <p>
        <input type="submit" value="Save" />
    </p>

</form>

Here is my controller file code:

public function indexAction()
    {
        $userform = new UserForm();
        $this->view->userForm = $userform;
        if($this->request->isPost()) {
            if($userform->isValid($_POST)) { 

            }

        }
    }

Any help is greatly appreciated. Thanks in advance.

1

There are 1 best solutions below

0
On

Will quote the docs.

By default messages generated by all the elements in the form are joined so they can be traversed using a single foreach, you can change this behavior to get the messages separated by the field:

foreach ($userform->getMessages(false) as $attribute => $messages) {
    echo "Messages generated by ", $attribute, ":", "\n";

    foreach ($messages as $message) {
        echo $message, "<br>";
    }
}

Or get specific messages for an element:

$messages = $userform->getMessagesFor("name");
foreach ($messages as $message) {
    echo $message, "<br>";
}

More information in the Docs.