0
votes

My need is to change behavior of edit form, for several content types.

The objective is: -After update button has been pressed, don't update the node but create a new one with values from old node. I could do that by passing old node's fields values to "/node/add/my_content" form but this require a lot of work (the forms are quite complicated) and on edit page i have already all values ready in my fields.

So i already tried hook_form_alter

function mymodule_form_alter (&$form, &$form_state, $form_id) {
  switch ($form_id) {
    case 'my_not_update_form':
      $node = $form_state['node'];
      if (!isset($node->nid) || isset($node->is_new)) {
      // This is a new node.
      }
      else {
        $new_node = new StdClass();
        $new_node->type = 'my_not_update_form';
        node_object_prepare($new_node);
        $new_node->uid = $user->uid;
        $new_node->language = 'und';
        $new_node->title = NULL;

        $form['vid']['#value'] = NULL;
        $form['nid']['#value'] = NULL;
        $form['created']['#value'] = $new_node->created;
        $form['changed']['#default_value'] = NULL;

        $form['#node'] = $new_node;
        $form['#entity'] = $new_node;
        $form_state['node'] = $new_node;
        $form_state['build_info']['args'][0] = $new_node;
      }
      break;
  }
}

So with the above code i'm able to create a new node but the "create date" parameter always stay the same as create date parameter of an old node and none of the above line can solve that problem.

2

2 Answers

0
votes

If you want to create an entirely new node when you submit edits to an existing node, then you want to use hook_node_presave(), which allows you to set any property of the node object before it's saved to the database.

In this example unsetting the nid and vid, and explicitly setting the is_new property will achieve this:

function my_module_node_presave($node) {
  unset($node->nid);
  unset($node->vid);
  $node->is_new = TRUE;
}

This will leave the existing node untouched and unedited, and will instead create an entirely new node.

0
votes

So to fully change the behavior of form update i give up on hook_form_alter() and instead i used hook_node_presave

function mymodule_node_presave($node) {
  if($node->is_new == FALSE || isset($node->nid)) {
    unset($node->nid);
    unset($node->vid);
    unset($node->vuuid);
    $node -> created = time();
    $node -> timestamp = time();
    $node-> is_new = TRUE;
    $node -> changed = time();
    unset($node->revision_timestamp);
    unset($node->num_revisions);
    unset($node->current_revision_id);
    unset($node->is_current);
    unset($node->is_pending);
    unset($node->revision_moderation);
    unset($node->date);
    unset($node->vuuid);
    unset($node->data);
  }
}