Tell me more ×
Drupal Answers is a question and answer site for Drupal developers and administrators. It's 100% free, no registration required.

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 = "[email protected]";
$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).

share|improve this question

1 Answer

up vote 3 down vote accepted

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);

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

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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