Score:0

Clarify difference between hook_form_TYPE_alter and hook_form_TYPE_EDIT_alter

ng flag

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?

Score:2
cn flag

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
  }
}
quantumized avatar
ng flag
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?
4uk4 avatar
cn flag
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()`.
mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.