Drupal 8 hook_form_alter example: user_login_form and user_register_form alter

This hook is used most often.

  1. **
  2. * Implements hook_form_alter().
  3. */
  4. function custom_module_form_alter(array &$form, FormStateInterface $form_state, $form_id) {
  5.  
  6. // Add few links to user login form
  7.  
  8. if ($form_id == 'user_login_form') {
  9.  
  10. $url = \Drupal\Core\Url::fromRoute('entity.node.canonical', ['node' => 182]);
  11. $project_link = Link::fromTextAndUrl(t('Registration'), $url);
  12. $project_link_r = $project_link->toRenderable();
  13.  
  14. $url = Url::fromRoute('user.pass');
  15. $project_link = Link::fromTextAndUrl(t('Reset password'), $url);
  16. $project_link_p = $project_link->toRenderable();
  17.  
  18. $form[] = array(
  19. '#type' => 'markup',
  20. '#markup' => render($project_link_r) . ' | ' . render($project_link_p),
  21. );
  22. }
  23.  
  24. // Custom submit handler when user register form submitted
  25.  
  26. if ($form_id == 'user_register_form') {
  27. $form['actions']['submit']['#submit'][] = 'user_register_form_custom_submit_handler';
  28. }
  29. }