Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Drupal - creating entries in file_managed

I have a custom content type with 2 custom fields: file (file) and list (status).

I can set the value of status by doing:

 $node = node_load($n, $r);
 $node->field_status[$node->language][0]['value'] = 1;
 node_save($node);

I want to create entries for field_file and file_managed (core table) for a file that is ALREADY on the server. I already know the MIME type, size and path of the file.

What is the proper way to achieve this?

like image 894
djdy Avatar asked Oct 31 '11 21:10

djdy


1 Answers

I would instantiate the file object manually and use file_save() to commit it (using an image file as an example):

global $user;
$file = new stdClass;
$file->uid = $user->uid;
$file->filename = 'image.png';
$file->uri = 'public://path/to/file/image.png';
$file->status = 1;
$file->filemime = 'image/png';

file_save($file);

You should then call file_usage_add() to let Drupal know your module has a vested interest in this file (using the nid from your $node object):

file_usage_add($file, 'mymodule', 'node', $node->nid);

Finally you can add the file to the node:

$node->field_file[$node->language][] = array(
  'fid' => $file->fid
);

Hope that helps

like image 186
Clive Avatar answered Sep 27 '22 23:09

Clive