5

I'm using drupal 7

I'm writing a custom hook_form_alter something like this

function mymodule_form_alter(&$form, &$form_state, $form_id){
    if($form_id == "rating_node_form")
        {
            // Do something
        }
}

it seems that both the node add form and the node edit form are using the same form ID. I'm wondering if there is a way to determine weather you are editing or adding a node and make changes to the form accordingly. Do they always have to be the same exact form?

2 Answers 2

10

node_object_prepare(), which is called from node_form() (the form builder for the node editing form), executes the following snippet to verify if a node is being added, or edited:

  // 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 your case, you could use code similar to the following one:

function mymodule_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == "rating_node_form") {
    $node = $form_state['node'];
    if (!isset($node->nid) || isset($node->is_new)) {
      // The node is new.
    }
  }
}
1
  • worked like a charm
    – user379468
    Dec 29, 2011 at 17:10
3

Or you can check if the second argument arg(1) == 'add'

function mymodule_form_alter(&$form, &$form_state, $form_id) {
  if($form_id == 'rating_node_form' && arg(1) == 'add') {
        // Do something
  }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.