7

I add a custom submit handler and now I want Redirect to custom route after form submitted.

This is what I used

use Drupal\Core\Form\FormStateInterface;
use Symfony\Component\HttpFoundation\Request;
use \Drupal\Core\Url;

function MYMODULE_form_alter(&$form, FormStateInterface $form_state, $form_id) {

    if ($form_id == 'node_trends_form' || $form_id == 'node_trends_edit_form') {

        foreach (array_keys($form['actions']) as $action) {
            if ($action != 'preview' && isset($form['actions'][$action]['#type']) && $form['actions'][$action]['#type'] === 'submit') {
                $form['actions'][$action]['#submit'][] = 'zyetondev_sync_trends_submit';
            }
        }
    }
}


function zyetondev_sync_trends_submit(array $form, FormStateInterface $form_state) {
    $url = Url::fromRoute('view.trends.page_1');
//    die(Url::fromRoute('view.trends.page_1')->toString());
    drupal_set_message("Done");
    $form_state->setRedirect($url);
}

Submit Handler getting run and redirect redirection work correctly, Problem is when we have ?destination= on Url, How can I force redirect even though ?destination= is on Url?

  • If I've understood your requirement correctly, you want to include query parameters as well during redirection? Correct me if wrong. – Yogesh Dec 20 '16 at 12:49
  • @Yogesh let's suppose you are on /admin/content , when try to edit a node ?destination=/admin/content added to url, I want to redirect my custom path even though ?destination= exists in url. – Yusef Mohamadi Dec 20 '16 at 12:57
10

The only correct way to do this is to alter the Request object and drop the destination.

In your submit callback:

\Drupal::request()->query->remove('destination');

Depending on the context, you might want to store it somewhere, for example pass it along to the URL you are redirecting to, so that it is respected again later.

See https://www.drupal.org/node/2325463 for a core issue that is doing exactly this to fix the preview button if a destination is given.

1

This code will help you.

 $url = \Drupal\Core\Url::fromRoute(
        'node.add',
         array('node_type' => $type->id()),
         array(
           'query' => array('destination' => $destination),
           'absolute' => TRUE,
         )
    );
   $form_state->setRedirect($url);
  • The code you are showing would not even redirect users. It is just creating a URL object, which doesn't do any redirect, by itself. – kiamlaluno Dec 20 '16 at 13:40

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.