Drupal 8 User Registration Form Alter
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 registration 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.,
/**
* Implementation of hook_element_info_alter().
*/
function module_name_element_info_alter(&$type) {
if (isset($type['password_confirm'])) {
$type['password_confirm']['#process'][] = 'module_name_process_password_confirm';
}
}
/**
* Function module_name_process_password_confirm() for editing label.
*/
function module_name_process_password_confirm($element) {
if ($_GET['q'] == 'user/register') {
if ($element['#array_parents'][0] == 'account') {
$element['pass1']['#title'] = 'New password'; //Set the title as per your needs
$element['pass1']['#attributes']['placeholder'] = t('Password');
$element['pass2']['#title'] = 'Password again';
$element['pass2']['#attributes']['placeholder'] = t('Confirm password');
}
}
return $element;
}
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 provide more control in the hands of developers to customize things as per their needs.