drupal 8 use hook form alter to add a link on register form

2k Views Asked by At

I'm really new to drupal 8. I want to add a link in register form.

I have been tried all the ways about hook_form_alter() and flush changes. It still doesn't work.

This is my module code.

<?php

/**
 * Implements hook_theme().
 */

function hook_register_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
     echo "alter the form"; exit;
}


2

There are 2 best solutions below

0
Harish ST On

Function hook_form_alter is used to perform alterations to the forms rendered. You should take care of the naming of hooks, since Drupal loads the hooks according to the name suggestions.

In your above code, you haven't provided the module name in function name. That is, the word hook should be replaced with your module name.

For Example, If your module name is foo. Then the above hook should be written as:

<?php

/**
 * Implements hook_form_alter().
 */
function foo_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
     echo "alter the form"; exit;
}

Also, in your code since you provided register in the code, I assume it is the ID of the form you are targeting to. For that, you should changed the code to:

<?php

/**
 * Implements hook_form_FORM_ID_alter().
 */
function foo_form_register_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
     echo "alter the form"; exit;
}

You could refer the difference between from the below official Drupal links: hook_form_alter hook_form_FORM_ID_alter

0
Vishnu Vijaykumar On
**
 * Implements hook_form_FORM_ID_alter().
 */
function hook_form_user_register_form_alter(&$form, FormStateInterface $form_state, $form_id) {
  // your code here
}

Replace hook in the function name with the module_name or the name of the module file you are writing the above code.

Note: The above alter is for the default register form provided by drupal 8