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

How to add CSS to form field if it fails validation

When a form field fails validation, we like to put a class on it so it can show up red (or some other similar visual cue). I'm pondering how to do this using Phalcon's form tools, and it occurs to me that other people must have done this before. Anyone have any thoughts? Thanks!

PS I know how to use getMessages and we are displaying flash messages at the top of the form. That part all works fine. This is a separate bit of eye-candy to apply styles to the error'd form fields themselves.



33.8k

Maybe:

$field->setAttribute('class', $field->getAttribute('class') . ' your-class');

Sounds promising! Will try.

Maybe:

$field->setAttribute('class', $field->getAttribute('class') . ' your-class');
edited Mar '15

In order to do this, I'll need to find a way to loop through the fields in the form and check each for validation status. Given what I've seen of Phalcon so far, that's probably doable. Normally, I just do this:

if (!$form->isValid($this->request->getPost())) {
  foreach ($form->getMessages() as $message) {
    $this->flashX->message('error', $message);
  }
}

...but in this case, looping the results of getMessages won't be enough; I need the fields themselves.



33.8k

Maybe you should try validating each field individually instead of all at the same time (I don't know if it is possible, I'm more of using Volt templates for forms, but I think it can be done).