I want to redirect to a node after comment form submit.
But I tried using hook_form_alter hook,the redirect not happen.

function pf_core_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id){
   $form['#submit'][] = 'pf_core_comment_comment_form_submit';

function pf_core_comment_comment_form_submit(&$form, \Drupal\Core\Form\FormStateInterface $form_state) {

Please help me to fix this issue.

3 Answers 3

$nid = 1; // lets pretend the node ID you want to redirect is 1.

$url = \Drupal\Core\Url::fromRoute('entity.node.canonical', ['node' => $nid]);
  • Thank you for your help.Can you tell me how to use this code,please?I insert this code to pf_core_comment_comment_form_submit function ,but nothing happend.
    – Shindou
    Commented Apr 14, 2017 at 14:28
  • 1
    Oh.This problem was solved.I should use $form['actions']['submit']['#submit'][] not is $form['#submit'][].Many thanks.
    – Shindou
    Commented Apr 14, 2017 at 15:15

If you ever need to redirect to a URL with parameters (rather than a fixed URL as in the example), a custom submit handler won't work because the $form object gets rebuilt, but you can append:

?destination= to $form['#action']

and it will redirect to that afterwards.

See question I asked.


A simple way to redirect to the same page, where the comment was submitted.

function mytheme_form_alter(&$form, FormStateInterface $form_state, $form_id) {
   if($form_id == 'comment_simple_form') {
      $form['#action'] .= '?destination=' . Drupal::service('path.current')->getPath();

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.