9

How do you alter or remove a form error produced by Drupal or another module on node insert/save, for a particular content type. I'm looking for a method which I can use in a module.

I've tried hook_node_validate(), but all I was able to do is to get errors and set errors.

enter image description here

13

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.'));
  }
}
  • Great answer! How would you go about changing the error text of - "Title field is required." (as pictured in the question)? That is without using string overrides. – timofey.com Mar 28 '13 at 0:52
  • In other words, I don't want to add validation, I just want to modify the error message of an existing validation.... maybe unset the existing validation and add a new one? – timofey.com Mar 28 '13 at 0:54
  • 1
    The existing validation is not a validation callback function; it's only that the field is "required". A combination of my last two above would remove the existing message and then add another type of validation. – pjcdawkins Mar 28 '13 at 10:44
  • I need to change only a validation message. Although I have implemented the above solution (by hook_form_alter ). I am getting two validation message. 1 one default and 2nd that I have written. Any suggestion @pjcdawkins – innovative kundan May 22 at 5:28
6

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.

4

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

message_alter(&$messages) {
}
  • Thanks. It probably not a good idea to use an unsupported module, but it can be used as a guide! – timofey.com May 8 '13 at 19:21
1

You can customize form error messages by using Field validation per entity field.

To do that, edit field settings, go to Validation and add a new validation rule (Required field). There, you should have textfield to set-up Custom error message for that field.

0

For Drupal 8, I was able to add a custom validate function that can actually examine the existing errors, and change the markup of the errors on a per case basis. In my case, I wanted to alter the error message from an entity_autocomplete field that was referencing users. If an invalid user was added, the validation error read, "There are no entities matching %name". Instead of the word "entities", I wanted to have it say "users", to be less scary and potentially confusing to users.

First, I use hook_form_alter() to add my validate function:

/**
 * Implements hook_form_alter().
 */
function my_module_form_alter(&$form, FormStateInterface $form_state, $form_id) {

      if (in_array($form_id, ['whatever_form_id_you_need_to_alter'])) {
        // Add entity autocomplete custom form validation messages alter.
        array_unshift($form['#validate'], 'my_module_custom_user_validate');
      }

Then, in the 'my_module_custom_user_validate' function:

/**
 * Custom form validation handler that alters default validation.
 * @param $form
 * @param \Drupal\Core\Form\FormStateInterface $form_state
*/
function my_module_custom_user_validate(&$form, FormStateInterface $form_state) {
      // Check for any errors on the form_state
      $errors = $form_state->getErrors();
      if ($errors) {
        foreach ($errors as $error_key => $error_val) {
          // Check to see if the error is related to the desired field:
          if (strpos($error_key, 'the_entity_reference_field_machine_name') !== FALSE) {
            // Check for the word 'entities', which I want to replace
            if (strpos($error_val->getUntranslatedString(), 'entities') == TRUE) {
              // Get the original args to pass into the new message
              $original_args = $error_val->getArguments();
              // Re-construct the error
              $error_val->__construct("There are no users matching the name %value", $original_args);
            }
          }
        }
      }
    }

Hope this helps!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.