im using the following code to upload an array of files when a node gets saved.

function mymodule_node_update($node){
 $result = $query;

 foreach ($result as $record) {
$url = ($record['src']);
$name_arr = explode('/', $url );
$filename = end($name_arr);
$filepath = system_retrieve_file($url, 'public://my_files/');

$file = new StdClass();
$file->uid = 1;
$file->uri = $filepath;
$file->filename = $filename;
$file->filemime = file_get_mimetype($file->uri);
$file->status = 1;  

$dest = file_default_scheme() . '://'.$filename; 
$file = file_copy($file, $dest); 
$file->display = 1;
$file->description = "";

This uploads the files to my public directory, and creates an entry into files_managed in my database.

But now how do I link those files to a filefield on the node im updating? I've tried variations of

  $node->field_file = (array)$file;

but nothing is working.

Thanks for any help

1 Answer 1


The field data has already been committed by the time hook_node_update() is called, so you won't be able to make any persistent alterations to field data in there.

Instead you could use hook_node_presave(), which is run before any data is written to the backend.

function mymodule_node_presave($node) {
  // Build up file object

  // Then add it to the node.
  $node->field_files[$node->language][] = (array)$file;

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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