We just starting out with Drupal 8 and very quickly we ran into our first problem.
How should I alter an existing form in Drupal 8?
We need to alter the save method for the node form to do a redirect to an other page. We want to alter the node form to become something like a multistep form. After the user creates new content they get redirected to a new form (we created) to get some more information.
We solved our problem implementing hook_entity_type_alter()
.
function mymodule_entity_type_alter(&$entity_info) {
$handlers = $entity_info['node']->get('handlers');
$handlers['form']['default'] = 'Drupal\mymodule\Form\MyExtendedNodeForm';
$handlers['form']['edit'] = 'Drupal\mymodule\Form\MyExtendedNodeForm';
$entity_info['node']->set('handlers', $handlers);
}
We then created a new form class that extends the node form and alter the save method.
class MyExtendedNodeForm extends NodeForm {
public function save(array $form, FormStateInterface $form_state) {
parent::save($form, $form_state);
$node = $this->entity;
$form_state->setRedirect('entity.regions.add_form', ['nid' => $node->id()]);
}
}
This works perfectly, but is it good? If another module does the same, our code does not get executed anymore.
hook_form_alter()
. If you just need to redirect the form, it's enough to add a form submission handler that does the redirect.save()
method" actually means. Does it mean changing the way data is saved, or just do a redirect? In the first case, the answer is more complex.