1

I have a site with a lot of hook form alters for node forms and I'm finding that I have to create two separate hook functions to affect both the node create and node edit forms.

For example, I have to put both:

module_events_form_node_event_form_alter()

and

module_events_form_node_event_edit_form_alter()

With the same functionality in both functions so that it covers both new and edited nodes. Is there a way to have one hook_form_alter() to cover both form conditions?

1 Answer 1

3

You can either use the full form ID with content type and operation or the base form ID node_form. This is without the operation but also missing the content type. So when you alter the base form you have to check for a specific content type if you don't want to alter all node forms:

/**
 * Implements hook_form_BASE_FORM_ID_alter().
 */
function mymodule_form_node_form_alter(&$form, FormStateInterface $form_state, $form_id) {
  $node = $form_state->getFormObject()->getEntity();
  if ($node->getType() == 'event') {
    // change the node form for the content type event and any operation
  }
}
2
  • To clarify, if I user form ID with content type then I must use two functions to account both new and edit forms but if I just use hook_form_alter and check for the type then I don't, correct? Commented May 18, 2022 at 15:08
  • 2
    The FORM_ID contains both content type + operation (create is default and default is omitted). The BASE_FORM_ID I've suggested contains neither of them and you can check them individually. BTW if you need the operation use $form_state->getFormObject()->getOperation().
    – 4uk4
    Commented May 18, 2022 at 15:58

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.