Fix for Creating a node with a FileField from file

  1. /**
  2.  * The following code create a node with a fieldfield attached file. The code almost works, the
  3.  * node is created and the file is imported by filefield (the file is copied to <drupal>/files and
  4.  * and entry is created in the DB). But the file is not listed when viewing the node until the node
  5.  * is edited manually.
  6.  *
  7.  * FileField creation code from http://drupal.org/node/292904#comment-956155
  8.  */
  9.  
  10. function import_document(&$document){
  11.   $node = new stdClass();
  12.   $node->type = 'folder';
  13.   node_object_prepare($node);
  14.   $node->title = $document->desc;
  15.   $node->created =  time();
  16.   $node->changed = $node->created;
  17.   $node->status = 1;
  18.   $node->promote = 0;
  19.   $node->sticky = 0;
  20.   $node->field_category[]['value'] = 58;
  21.   $node->field_folderfiles[] = _import_file($node, 'field_folderfiles', '/tmp/import/'.$document->filename);
  22.   node_save(node_submit($node));
  23. }
  24.  
  25. function _import_file($node, $field, $filename) {
  26.   if(is_string($field)) $field = content_fields($field, $node->type);
  27.   $validators = array();
  28.   $save_path = _import_widget_files_directory($field, $node);
  29.   return field_file_save_file($filename, $validators, $save_path);
  30. }
  31.  
  32. function _import_widget_files_directory($field, $node) {
  33.   $widget_file_path = $field['widget']['file_path'];
  34.   if (module_exists('token')) {
  35.     global $user;
  36.     $widget_file_path = token_replace($widget_file_path, 'user', $user);
  37.     if($node) {
  38.       $widget_file_path = token_replace($widget_file_path, 'node', $node);
  39.     }
  40.   }
  41.   return file_directory_path() .'/'. $widget_file_path;
  42. }

Submit Fix

Any tags you'd like to associate with your code, delimitered by commas (example: Views, CCK, Module, etc).
Select the syntax highlighting mode to use.