Adding CSS class ‘error’ when rendering with form macros

Notice: This thread is very old.
petr.pavel
Member | 535
+
+1
-

I've just spent some time figuring out how to add a CSS class ‘error’ to inputs that have an error.
It's great that we can add errors to particular elements but the feature is incomplete without being able to render erroneous elements differently.

Let's start with the most awkward way:

{input email class => implode(' ', array_keys($_form['email']->getControlPrototype()->class)).($_form["email"]->hasErrors() ? ' error')}

This can be made better by splitting into two steps:

{if $_form["email"]->hasErrors()}
  {var $_form['email']->getControlPrototype()->class['error'] = true}
{/if}
{input email}

Still however, it sucks. The final method is to add the class in the form handler, not in Latte. The main benefit is that you can do it in one swoosh.

use Nette\Application\UI\Form;

$form->onError[] = $this->error;

public function error(Form $form)
{
  foreach ($form->getControls() as $control) {  /** @var $control Nette\Forms\Controls\BaseControl */
    if ($control->hasErrors()) {
      $control->getControlPrototype()->class['error'] = true;
    }
  }
}

I wonder if anyone knows of a better way. Also, is there a problem with adding the class automatically by Nette?

Edit: It would make sense to add the class with netteForms.js too.

Last edited by petr.pavel (2014-04-17 17:44)