10

This is my second question about my issues with creating custom migration script.

I am creating only new nodes and don't care about updates.

Code:

        $node = new stdClass();
        $node->type = 'migrate';
        $node->title = $content['title'];
        $node->language = LANGUAGE_NONE;

        $node->created = (int) date('U',strtotime($content['created']));

        $modified = $content['modified'];               
        if (! empty($modified) && $modified != '0000-00-00 00:00:00') {
            $modified = (int) date('U',strtotime($modified));
        } else {
            $modified = 0;
        }               
        $node->changed = $modified;

        node_object_prepare($node);

        #some lines later
        node_save($node);

E.g my $modified is set to 0 and after save I see updated column of this node row in admin content list with current datetime value.

1 Answer 1

15

You should be able to preserve the original changed time by first setting a custom property on the node object, say $node->modified, in your migration script prior to calling node_save(), and then implementing the node_presave hook:

/**
 * Implements hook_node_presave().
 */
function mymodule_node_presave($node) {
  $node->changed = $node->modified;
}

This will work since node_save() sets $node->changed prior to calling all modules which implement hook_node_presave().

4
  • Yes it works 100% :)
    – Codium
    Commented Aug 12, 2012 at 11:19
  • 1
    Suspect I'll get shot down for this, but if like me you're running a short-lived script via drush that's not part of a module and you don't want to implement a module just to implement a hook etc. then it works to db_query('UPDATE {node} SET created=:created, changed=:changed WHERE nid=:nid', array(':created'=>$whatever,':changed'=>$whatever,':nid'=>$node->nid)); after saving. Commented Jul 21, 2014 at 10:36
  • I hate that we have to do something as awkward as a hook (awkward because the change happens in a completely different code segment), but that's drupal's fault, not yours. +1 Commented Dec 16, 2014 at 1:48
  • You can also use $node->original->changed instead of setting a custom property like $node->modified. Disable the module after using otherwise the changed date will never be updated. Commented May 25, 2021 at 13:57

Your Answer

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

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