Tuesday 29 September 2015

Filter out specific errors during validation or modify any error message

This is one of the way to alter the error message in any of the forms.

In my example I have added a custom validate to validate the user login functinality.

1. filter out validation
<?php/**
 * Custom Form Validation.
 * Removes all form validation errors caused by a 'foo][bar' form element.
 */function my_module_form_validate($form, &$form_state) {
  $errors = form_get_errors();
  if ($errors) {
    // Clear errors.
    form_clear_error();
    // Clear error messages.
    $error_messages = drupal_get_messages('error');
    // Initialize an array where removed error messages are stored.
    $removed_messages = array();

    // Remove all errors originated by the 'foo][bar' element.
    foreach ($errors as $name => $error_message) {
      if ($name == 'foo][bar') {
        $removed_messages[] = $error_message;
        unset($errors[$name]);
      }
    }

    // Reinstate remaining errors.
    foreach ($errors as $name => $error) {
      form_set_error($name, $error);
      // form_set_error() calls drupal_set_message(), so we have to filter out
      // these from the error messages as well.
      $removed_messages[] = $error;
    }

    // Reinstate remaining error messages (which, at this point, are messages that
    // were originated outside of the validation process).
    foreach (array_diff($error_messages['error'], $removed_messages) as $message) {
      drupal_set_message($message, 'error');      
    }
  }
}?>
 
2. To modify the error message : 
 
 in the above code replace this code
 
 // Remove all errors originated by the 'foo][bar' element.
    foreach ($errors as $name => $error_message) {
      if ($name == 'foo][bar') {
        $removed_messages[] = $error_message;
        unset($errors[$name]);
      }
    }
 
with this one 
 // Remove all errors originated by the 'foo][bar' element. used this in user form alter custom validation
    foreach ($errors as $name => $error_message) {
      if ($name == 'name') {
       $errors[$name] = "<p>We can't find a user with that email.";
        $removed_messages[] = $error_message;
       // unset($errors[$name]);
      }
    } 
 This will replace the default error message "Sorry, Unrecognized username and password with the above text
 
Reference link : https://api.drupal.org/comment/28464#comment-28464  

Drupal - How to create or apply patches

This Url has a definitive guide for applying patch in the  drupal.org

https://www.drupal.org/project/drupal/git-instructions