2

I have a form with ajax callback as following , on each submit token is not varying , it remains constant for all submit .

wall.routing.yml

wall.commentform:
  path: '/commentform'
  defaults:
    _title: 'Comment form'
    _form: '\Drupal\wall\Form\WallCommentPost'
  requirements:
    _permission: 'access content'
    _csrf_token: 'TRUE'

In from as following

WallCommentPost.php

$ajax = [
  'callback' => [$this, '_wall_comment_ajax_form_post'],
  'wrapper' => 'field-type-replace-comment',
  'event' => 'click',
  'progress' => array(
    'type' => 'throbber',
    'message' => '',
  )
];

$form['wall_submit'] = [
  '#type' => 'submit',
  '#value' => 'Submit',
  '#ajax' => $ajax,
  '#prefix' => '<div class="col-12 p-1 d-flex justify-content-between"><div class="file_name_insert file_name_insert_data-' . $nid . ' pl-4 text-truncate"></div>',
  '#suffix' => '</div>',
  '#attributes' => array(
    'class' => array(
      'btn',
      $ajax_class,
      'd-none',
      'subbtn-' . $nid
    ),
    'disabled' => 'disabled'
  ),
];
$url = Url::fromRoute('wall.commentform');
$token = \Drupal::csrfToken()->get($url->getInternalPath());

$form['#action'] = Url::fromRoute('wall.commentform')->setOption('query', [FormBuilderInterface::AJAX_FORM_REQUEST => 1, 'token1' => $token])->toString();
5
  • 1
    I see $token is commented out, is it intentional ? or you missed it ? Commented Jun 10, 2021 at 10:49
  • By default that URL itself generating token , I just tested this way by forcefully adding token ,still it remains as a constant value .
    – Monika
    Commented Jun 10, 2021 at 14:17
  • I can't understand what you're trying to do. I can see how you're trying to do it, but I don't understand what your goal is, or what is working contrary to what is expected. Not enough information.
    – Jaypan
    Commented Jun 10, 2021 at 16:16
  • May be it helps drupal.stackexchange.com/a/268262 ? Commented Jun 11, 2021 at 4:15
  • CSRF token should vary on each submit request , that is my goal , as of now the CSRF token passing in the URL remains constant . how to vary the token value on each submit request ?
    – Monika
    Commented Jun 11, 2021 at 17:22

1 Answer 1

0

After further digging found out the cause for CSRF token not varying.

CSRF token is dependent on session. So until the session is same CSRF token stays same.

Logout and login again and submit the form, you will get new token.

There is an issue reported in Drupal.org for the same even though it is fixed for Drupal 8, it is not working as expected.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.