0

I have a node that includes a series of embedded views. When displaying, I have to pass a value via URL arguments (http://example.org/node/x?id=y), so that the views can get the appropriate information. The user needs to be able to edit this node, but when they save and return to the node it has lost the id=y part and the display is incomplete.

I know I can use hook_form_alter() to redirect, but I can't figure out how can I redirect after the node is saved using that URL argument?

3
  • @apaderno - Thank you for editing my post to make clear.
    – gmak
    Aug 1, 2021 at 13:52
  • What version of Drupal are you using? Aug 2, 2021 at 7:08
  • 1
    I am using Drupal 9
    – gmak
    Aug 2, 2021 at 7:24

1 Answer 1

0

Using hook_form_alter(), you can add a submission handler that sets the redirection. The code for the submission handler would be similar to the following one.

function mymodule_node_edit_submit(array &$form, FormStateInterface $form_state) {
  $node = $form_state->getFormObject()->getEntity();
  $id = \Drupal::request()->query->get('id');
  $form_state->setRedirect('entity.node.canonical', ['node' => $node->id()], [query => ['id' => $id]]);
}

The code for hook_form_BASE_FORM_ID_alter() would simply be the following one.

function mymodule_form_node_form_alter(&$form, FormStateInterface $form_state) {
  $node = $form_state->getFormObject()->getEntity();

  // Since this hook is invoked for every node, check its content type.
  if ($node->getType() == 'the content type you are interested in') {
    $form['actions']['submit']['#submit'][] = 'mymodule_node_edit_submit';
  }
}

The hook_form_FORM_ID_alter() implementation should be named mymodule_form_node_<content_type_machine_name>_alter(). (Replace mymodule with the module machine name, <content_type_machine_name> with the content type machine name.) In this case, since the hook is invoked only for a content type, it doesn't need to check the node content type before adding the submission handler.

1
  • Something is not working. If my url is http://example.org/node/123?id=57, after submitting the form it is redirected to http://example.org/node/123?id. So it seems that the id query parameter is not getting added. If I do a dpm($id) in either of the functions, it shows as NULL - which makes me think that the query is not getting captured from the original node. Have I missed something?
    – gmak
    Aug 2, 2021 at 8:12

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.