Hello, I am fairly new to Drupal and while I have seen various comments about this concept, none seem to apply in this scenario yet. We have a custom content type (in D7) that requires attaching 'n' number of files to a node (.PDF, .DOC, .ZIP, etc). So, as described here, we have a File field configured on the content type to support multiple files. This appears to be working fine through the form, but our greater need is to associate files through custom code (via an offline trigger).

Essentially, we have accessible files on our file system and, during "offline" processing, these need to be associated in Drupal to existing nodes.

Code snippet:

  $file_obj = new stdClass();
  $file_obj->uid = $uid;
  $file_obj->filename = $name;
  $file_obj->uri = file_create_url($file);
  $file_obj->filemime = file_get_mimetype($name);
  $file_obj->filesize = $filesize;
  $file_obj->status = FILE_STATUS_PERMANENT;
  $file_obj->timestamp = (string) time();
  $file_obj = file_save($file_obj);

  $node->field_files[$node->language][$file_obj->fid] = $file_obj;
  node_save($node);

The file_save() appears to be working and stores a record in the file_managed table. However, the node_save($node) fails (the offline process aborts) and I am not sure why yet as no exception is thrown. Without the node_save() call, the offline process (which is quite complicated) works as expected.

Before saving the node, the $node association to $file_obj appears to be set the same as when associating a file through the UI form. And when saving the node through the form, the file_usage table gets a new row for the association, but not sure if that relationship functionality is triggered through node_save()? We don't really care about what happens under the Drupal hood (unless we have to) we just want to properly save a file to a node programmatically.

TIA

Comments

nevets’s picture

I believe

$node->field_files[$node->language][$file_obj->fid] = $file_obj;

should be

$node->field_files[$node->language] = $file_obj->fid;
mbnsorg’s picture

nevets, the array index is to support multiple files per node.

I changed a few things and now it seems "working".

First, added:
$file_obj->display = '1';

And then:
$node->field_files[$node->language][$index] = get_object_vars($file_obj);

Cheers.