3

I know we can distinguish between new/edit manner of node in form_alter with following snippet in drupal 7

function mymodule_form_node_form_alter(&$form, &$form_state) {
  $node = $form_state['node'];

  if (!isset($node->nid) || isset($node->is_new)) {
    // This is a new node.
  }
  else {
    // This is not a new node.
  }
}

Now I'm looking for the equivalent solution for Drupal 8.

How can detect the form is for editing an existing node, or creating a new node?

  • you could just grab the url. – No Sssweat Dec 17 '16 at 10:19
  • 1
    @NoSssweat just think there is something like formblock etc, in that manner URL is not node/nid/edit but still this solution should work – Yusef Mohamadi Dec 17 '16 at 10:24
  • 1
    see the updated accepted answer to Difference between create new and edit node in form alter – No Sssweat Dec 17 '16 at 10:35
  • 1
    You didn't read the updated accepted answer carefully? :| – No Sssweat Dec 17 '16 at 10:38
  • 1
    @NoSssweat no I didn't see it :D 🙈🙈🙈, now can you provide a question for future visitors of this question? – Yusef Mohamadi Dec 17 '16 at 10:40
11

You can use method $form_state->getFormObject()->getEntity() like this

function mymodule_form_node_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
  $node = $form_state->getFormObject()->getEntity();
  if ($node->isNew()) {
    // This is a new node.
  }
  else {
    // This is not a new node.
  }
}

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.