Skip to main content
knackforge blog knowledge base

Altering labels in User registration form

It is apparent that we modify any form in drupal by implementing hook_form_alter(). But there are cases when even the hook_form_alter() cannot offer a solution in altering the form fields. I recently faced such a situation, when I was trying to empty the labels in the password & confirm password fields in the user registeration form in Drupal 7.
 
So it was time to get my hand dirty by digging some other alternate Drupal API & found hook_element_info_alter(), which helped me complete my task.
 
Implement hook_element_info_alter() in the custom module & call a process function to alter the labels.,
 
  1. /**
  2.  * Implementation of hook_element_info_alter().
  3.  */
  4. function module_name_element_info_alter(&$type) {
  5.   if (isset($type['password_confirm'])) {
  6.     $type['password_confirm']['#process'][] = 'module_name_process_password_confirm';
  7.   }
  8. }
  9.  
  10. /**
  11.  * Function module_name_process_password_confirm() for editing label.
  12.  */
  13. function module_name_process_password_confirm($element) {
  14.   if ($_GET['q'] == 'user/register') {
  15.     if ($element['#array_parents'][0] == 'account') {
  16.       $element['pass1']['#title'] = 'New password'; //Set the title as per your needs
  17.       $element['pass1']['#attributes']['placeholder'] = t('Password');
  18.       $element['pass2']['#title'] = 'Password again'
  19.       $element['pass2']['#attributes']['placeholder'] = t('Confirm password');
  20.     }
  21.   }
  22.   return $element;
  23. }
 
Apart from altering the labels, the hook_element_info_alter() can be used in altering any kind of information returned by any module. This does provides more control in the hands of developers to customize things as per the needs.