Take the 2-minute tour ×
Drupal Answers is a question and answer site for Drupal developers and administrators. It's 100% free, no registration required.

I'm not much of a coder so I'm having a real hard time figuring this out.

I have a custom module and I'm trying to override user_account_form_validate() (from user.module) so that I can add a watchdog entry every time a specific instance of form_set_error() is called:

elseif ((bool) db_select('users')->fields('users', array('uid'))->condition('uid', $account->uid, '<>')->condition('name', db_like($form_state['values']['name']), 'LIKE')->range(0, 1)->execute()->fetchField()) {
  form_set_error('name', t('The name %name is already taken.', array('%name' => $form_state['values']['name'])));
}

I need to do this because sometimes the Email registration module causes this error to fire and I want to make sure that this doesn't occur; so, to ensure users aren't seeing this error, I want to log it in watchdog if it occurs.

I know I can hack core and add the following line just after form_set_error:

watchdog('mymodule', 'Registration error: %name was already registered.', array('%name' => $form_state['values']['name']), WATCHDOG_ALERT);

But how I can I do this without hacking core? I tried various permutations of function

function mytheme_user_register_form_validate (&$form, &$form_state) {}

in a custom module but I couldn't successfully get Drupal to use my function instead of the core one.

share|improve this question

1 Answer 1

up vote 1 down vote accepted

To add a new validation handler to a form, you need to implement hook_form_alter(). In your case, I would use the following code, which adds an extra validation handler that is executed before the other ones added by the User module.

function mymodule_form_user_register_form_alter(&$form, &$form_state) {
  array_unshift($form['#validate'], 'mymodule_user_register_validate');
}

function mymodule_user_register_validate($form, &$form_state) {
  $account = $form['#user'];

  if (isset($form_state['values']['name'])) {
    if ($error = user_validate_name($form_state['values']['name'])) {
      // This is intentionally empty.
    }
    elseif ((bool) db_select('users')->fields('users', array('uid'))->condition('uid', $account->uid, '<>')->condition('name', db_like($form_state['values']['name']), 'LIKE')->range(0, 1)->execute()->fetchField()) {
      // Log the error with watchdog().
    }
  }
}
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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