Tos Web Developer provides insights, tutorials, and advice around topics including content strategy, design, Drupal Development, Drupal Custom Module Development, Drupal 8 Custom themes, PHP, Server, Twig, and more

I used the following hook_form_alter code to add a token:

 use Drupal\Component\Utility\Html;
/**  
  * Implements hook_form_alter().  
  */  
  function resume_form_alter(&$form, Drupal\Core\Form\FormStateInterface $form_state, $form_id) {  
   // Adding custom validation for the welcome page type field.  
   if ($form_id == 'user_login_form') {  
    // Do some stuff.  
     $form_id == 'user_login_form';  
   }  
   if(!isset($form['#token'])) {  
    $form['#token'] = $form_id;  
    $form['form_token'] = array(  
     '#id' => Html::getUniqueId('edit-' . $form_id . '-form-token'),  
     '#type' => 'token',  
     '#default_value' => resume_generate_token($form['#token']),  
    );  
   }  
  }  

Then I used this custom function to generate the token for me:

  function resume_generate_token($form_id){  
   $secret = 'my-unique-string'; //could be todays date, whatever you want to make it.  
   // return drupal_hmac_base64($form_id, $secret. drupal_get_private_key() . drupal_get_hash_salt());  
   $hmac = base64_encode(hash_hmac('sha256', $form_id, $secret, TRUE));  
   // Modify the hmac so it's safe to use in URLs.  
   return str_replace([  
    '+',  
    '/',  
    '=',  
   ], [  
    '-',  
    '_',  
    '',  
   ], $hmac);  
  }  

Then I also wrote a utility function that checks to see if the token coming from an anonymous form is valid:

  function resume_check_valid_token($form_token, $form_id){  
   return ($form_token == resume_generate_token($form_id));  
  }  

Hope this helps

The final output is you can check on the inspected element as I have given in the below screenshot




No comments:

Post a Comment

| Designed And Blog Post by www.toswebdeveloper.com