The form used in the login form and in the login page is the one implemented by the Drupal\\user\\Form\\UserLoginForm
class. This means that the form ID to check in hook_form_alter()
or hook_form_FORM_ID_alter()
is the same in both the cases.
Implementing hook_block_view_BASE_BLOCK_ID_alter()
, it's possible to alter the rendering output for a block, including the login block.
function mymodule_block_view_user_login_block_alter(array &$build, \Drupal\Core\Block\BlockPluginInterface $block) {
// Alter the login form, which is stored in $build['user_login_form'].
// This example changes the size of the name and password fields.
$build['user_login_form']['name']['#size'] = 18;
$build['user_login_form']['pass']['#size'] = 18;
}
The plugin ID for the login block is given in the annotation for the UserLoginBlock class. The content of the $build
array is returned from UserLoginBlock::build()
.
$form = \Drupal::formBuilder()->getForm('Drupal\\user\\Form\\UserLoginForm');
unset($form['name']['#attributes']['autofocus']);
unset($form['name']['#description']);
unset($form['name']['#attributes']['aria-describedby']);
unset($form['pass']['#description']);
unset($form['pass']['#attributes']['aria-describedby']);
$form['name']['#size'] = 15;
$form['pass']['#size'] = 15;
$placeholder = 'form_action_p_4r8ITd22yaUvXM6SzwrSe9rnQWe48hz9k1Sxto3pBvE';
$form['#attached']['placeholders'][$placeholder] = [
'#lazy_builder' => [
'\\Drupal\\user\\Plugin\\Block\\UserLoginBlock::renderPlaceholderFormAction',
[],
],
];
$form['#action'] = $placeholder;
$items = [];
if (\Drupal::config('user.settings')->get('register') != UserInterface::REGISTER_ADMINISTRATORS_ONLY) {
$items['create_account'] = [
'#type' => 'link',
'#title' => $this->t('Create new account'),
'#url' => Url::fromRoute('user.register', [], [
'attributes' => [
'title' => $this->t('Create a new user account.'),
'class' => [
'create-account-link',
],
],
]),
];
}
$items['request_password'] = [
'#type' => 'link',
'#title' => $this->t('Reset your password'),
'#url' => Url::fromRoute('user.pass', [], [
'attributes' => [
'title' => $this->t('Send password reset instructions via email.'),
'class' => [
'request-password-link',
],
],
]),
];
return [
'user_login_form' => $form,
'user_links' => [
'#theme' => 'item_list',
'#items' => $items,
],
];