Drupal - Difference between create new and edit node in form alter

If you look at the code of node_object_prepare(), which is called from node_form() (the form builder for the node edit/create form), you will see it contains the following code.

  // If this is a new node, fill in the default values.
  if (!isset($node->nid) || isset($node->is_new)) {
    foreach (array('status', 'promote', 'sticky') as $key) {
      // Multistep node forms might have filled in something already.
      if (!isset($node->$key)) {
        $node->$key = (int) in_array($key, $node_options);
      }
    }
    global $user;
    $node->uid = $user->uid;
    $node->created = REQUEST_TIME;
  }

In an implementation of hook_form_BASE_FORM_ID_alter(), it is enough to use code similar to the following one.

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.
  }
}

If the node is new, then the form is creating a node; if the node is not new, then the form is editing an existing node.

In Drupal 8, every class implementing EntityInterface (including the Node class) override the EntityInterface::isNew() method. Checking if a node is new becomes as easy as calling $node->isNew(). Since in Drupal 8 there isn't $form_state['node'] anymore, the code becomes the following.

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

  if ($node->isNew()) {
    // This is a new node.
  }
  else {
    // This is not a new node.
  }
}

Yes, you have to check if the node ID exists or not.


/**
 * Implementation of hook_form_alter().
 */
function MY_MODULE_form_alter(&$form, $form_state, $form_id) {
  if ($form['#node'] && $form['#node']->type .'_node_form' === $form_id) {
    // Is node form.

    if ($form['#node']->nid) {
      // Is node edit form.
    }
  }
}

Tags:

Forms