1

I need to programmaticly create a node in Drupal 7 i followed availible tutorials and came up with this code:

define('DRUPAL_ROOT', getcwd());
require_once DRUPAL_ROOT . '/includes/bootstrap.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);


$md5 = md5(strtotime("now"));

$field_customer_name = 'NAthtn';
$field_customer_email = "something@gmail.com";
$field_downloads_count_left = '11';

$filename = 'file123.zip';
$filepath = 'sites/default/files/private/file123.zip';

// Create managed File object and associate with file field.
$file = new StdClass();
$file->uid = 1;
$file->uri = $filepath;
$file->filename = $filename;
$file->filemime = file_get_mimetype($file->uri);
$file->status = 1;  
$file = file_copy($file, 'public://', FILE_EXISTS_REPLACE);

$node = new stdClass();
$node->type = 'download';
node_object_prepare($node);

$node->title    = $md5;
$node->language = LANGUAGE_NONE;

$node->field_customer_name[$node->language][0]['value'] = $field_customer_name;
$node->field_customer_email[$node->language][0]['value'] = $field_customer_email;
$node->field_downloads_count_left[$node->language][0]['value'] = $field_downloads_count_left;
$node->field_file[$node->language][0]['value'] = (array)$file;

$path = $md5;
$node->path = array('alias' => $path);

node_save($node);

I am getting the following error in the log:

PDOException: SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'fid' cannot be null: INSERT INTO {file_usage} (fid, module, type, id, count) VALUES (:db_insert_placeholder_0, :db_insert_placeholder_1, :db_insert_placeholder_2, :db_insert_placeholder_3, :db_insert_placeholder_4); Array ( [:db_insert_placeholder_0] => [:db_insert_placeholder_1] => file [:db_insert_placeholder_2] => node [:db_insert_placeholder_3] => 51 [:db_insert_placeholder_4] => 1 ) in file_usage_add() (line 664 of /home/content/16/5470416/html/download/includes/file.inc).

1 Answer 1

3

replace

$node->field_file[$node->language][0]['value'] = (array)$file;

with

$node->field_file[$node->language][] = (array)$file;

Also, add $node->validated = TRUE; before node_save($node);

2
  • 2
    +1 for the first bit, adding $node->validated is unnecessary though
    – Clive
    Apr 29, 2012 at 10:07
  • 1
    Thanks a lot!!! :) i also had to add display property, or else it gave me other error... Apr 29, 2012 at 16:47

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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