1

When a user add a comment on a node, I would like to prevent the page reload.

I added a form_alter in my theme

function theme_form_alter(&$form, &$form_state, $form_id) {
    switch($form_id) {
      case 'my_form_id':
        $form_state['redirect'] = false;
      break;
  }
}

But this is not working.

I also tried to replace $form_state['redirect'] = false by $form_state['redirect'] = false but it seems to be the Drupal 7 way to do this.

how could I achieve that on Drupal 8 ?

EDIT

I tried to use a submission handler

function theme_form_alter(&$form, &$form_state, $form_id) {
        switch($form_id) {
          case 'my_form_id':
            $form['#submit'][] = 'theme_form_submit';
          break;
      }
    }

function theme_form_submit(array $form, FormStateInterface $form_state){
    $form_state->disableRedirect();
}

But it's still not working.

2

Use FormStateInterface::disableRedirect(), e.g.

$form_state->disableRedirect();

Make sure you run that code in a submit handler for the form, not in the form alter hook.

  • I also tried this one but it didn't changed a thing. Do I need to import something to be able to use it ? (I didn't import anything since no error was rendered) – Tibo Jun 28 '18 at 9:34
  • I was just detailing the replacement for $form_state['redirect'] = false, re-reading your question there's a chance you actually want to install a module like drupal.org/project/ajax_comments. Adding a comment submits a form, which isn't a redirect, it's a standard POST request. To stop that happening you'll need to implement the same functionality in AJAX – Clive Jun 28 '18 at 9:48
  • Just replacing $form_state['redirect'] = false by $form_state->disableRedirect(); would be enough for me if it prevent redirection after submission. But it's currently not working, maybe because I need to import FormStateInterface, is it necessary ? But I will still give a look at that module – Tibo Jun 28 '18 at 10:07
  • I just noticed you're running the code in hook_form_alter - you need to run it in a submit handler for the form. Other submit handlers (core and contrib ones) run after the form alter upon submission, nuking your change. You need to disable the redirect after those have run – Clive Jun 28 '18 at 10:13
  • No you don't need to import any namespaces - if you were trying to use something that was unavailable PHP would let you know about it in certain terms – Clive Jun 28 '18 at 10:14

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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