Drupal - How do you alter a form error?

Altering strings

To change the text of a single string, the simplest method is to use the String Overrides module. That would allow you to replace the string:

"!name field is required."

with (for example):

"The field '!name' is required."

Altering form fields

If you want to make a field not required, use a normal hook_form_alter() implementation:

/**
 * Implements hook_form_FORM_ID_alter().
 */
function mymodule_form_node_form_alter(&$form, &$form_state) {
  $node = $form['#node'];
  if ($node->type == 'my_custom_type') {
    $form['title']['#required'] = FALSE;
  }
}

Changing the way a form is validated

Forms have validation functions specified in the $form['#validate'] array. And form elements have functions specified in $form['element_key']['#element_validate'].

You can specify your own like this:

/**
 * Implements hook_form_FORM_ID_alter().
 */
function mymodule_form_node_form_alter(&$form, &$form_state) {
  $form['title']['#element_validate'][] = 'mymodule_validate_node_title';
}

/**
 * Validate the node title to prevent ALL CAPS.
 */
function mymodule_validate_node_title($element, &$form_state, $form) {
  if (preg_match('/^[A-Z]+$/', $element['#value'])) {
    form_error($element, t('You may not enter titles in ALL CAPS.'));
  }
}

Since the string used for that error message is "!name field is required." using the String Overrides module or changing the string to use in the settings.php file would have the effect to change the string used for every required form field.

If you want to alter the error string shown for the title when the title has not been entered, you can:

  • Add a form validation handler to the node edit form, using hook_form_alter()
  • In that form validantion handler:

    • Verify the content of $form['title'] (where $form is set using $form = &drupal_static('form_set_error', array());, and change it to the string you want when it is 'Title field is required.'
    • Verify $_SESSION['messages']['error'] (an array) contains the string 'Title field is required.' and change it to the string you want to show

Avoiding to show the error is easier: Just set the #required property to FALSE, and Drupal will not show that error message.


For drupal 7 you can download this module http://drupal.org/node/1209450 in zip it will give you this hook.

message_alter(&$messages) {
}

Tags:

Forms

7