0

i am new to drupal and trying to migrate same pages to drupal. I am able to create one node via druapals API, but when trying to create more nodes in a loop it doesn't work...

This is the working code:

    define('DRUPAL_ROOT','/var/www');
    require '/var/www/includes/bootstrap.inc';
    drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);        


    #construct the new node object
    $node = new stdClass();

    #specify node properties
    $node->uid = 1;
    $node->title = "new node";
    $node->log ="";
    $node->status = 1;
    $node->comment = 1;
    $node->promote = 0;
    $node->sticky = 0;
    $node->type = 'veranstaltung';
    $node->language = 'und';
    $node->created = time();
    $node->changed = $node->created;
    $node->tnid=0;
    $node->translate=0;
    $node->body['und'][0]['value']="<h1>content</h1>";
    $node->body['und'][0]['format']="filtered_html";
    $node->body['und'][0]['safe_value']="<h1>content</h1>";

    #save node
    node_save($node)    

If i put this in a for-loop and change the body and title each iteration it doesn't work.. The code is inside an external php script. Even copy the code and paste behind it again with other body and title does not work.

Thanks a lot

2
  • Better run this script using Drush. It's very easy to use it for running scripts. It'll automaticaaly bootstrap Drupal.
    – AgA
    Commented Jun 16, 2013 at 16:34
  • 2
    Objects are passed by reference in PHP; therefore $node->nid is being set after your first go around the for loop. If $node->nid is set, no new node is created, so, I'd unset($node->nid) after each node_save() and give it another try.
    – Jimajamma
    Commented Jun 16, 2013 at 19:51

2 Answers 2

1

Objects are passed by reference in PHP; therefore $node->nid is being set after your first go around the for loop. If $node->nid is set, no new node is created, so, I'd unset($node->nid) after each node_save() and give it another try.

1

Try function node_object_prepare()

$node = new stdClass();
$node->type = 'thing';
node_object_prepare($node);
$node->title = 'Test thing';
// ...more node properties...
node_save($node);
$nid = $node->nid;
print 'nid of the node I just created: ' . $nid;

You can also include your code in a custom module in a hook_init() or a hook_cron(), you'll not need to boostrap drupal

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.