Fix for Creating a node with a FileField from file

  1. /**
  2.  * FileField creation code from http://drupal.org/node/292904#comment-956155
  3.  */
  4. function import_document(&$document){
  5.   $node = new stdClass();
  6.   $node->type = 'folder';
  7.   node_object_prepare($node);
  8.   $node->title = $document->desc;
  9.   $node->created = _import_get_time($document->date);
  10.   $node->changed = $node->created;
  11.   $node->status = 1;
  12.   $node->promote = 0;
  13.   $node->sticky = 0;
  14.   $node->field_category[]['value'] = 58;
  15.   $node->field_folderfiles[] = _import_file($node, 'field_folderfiles', '/tmp/cdm/'.$document->filename);
  16.   var_export($node);
  17.   print("\n");
  18.   //print("Content created for '$node->title'.");
  19. }
  20.  
  21. function _import_file($node, $field, $filename) {
  22.   if(is_string($field)) $field = content_fields($field, $node->type);
  23.   $validators = array_merge(filefield_widget_upload_validators($field), imagefield_widget_upload_validators($field));
  24.   $save_path = _import_widget_files_directory($field, $node);
  25.   return field_file_save_file($filename, $validators, $save_path);
  26. }
  27.  
  28. function _import_widget_files_directory($field, $node) {
  29.   $widget_file_path = $field['widget']['file_path'];
  30.   if (module_exists('token')) {
  31.     global $user;
  32.     $widget_file_path = token_replace($widget_file_path, 'user', $user);
  33.     if($node) {
  34.       $widget_file_path = token_replace($widget_file_path, 'node', $node);
  35.     }
  36.   }
  37.   return file_directory_path() .'/'. $widget_file_path;
  38. }

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.