Drupal - creating entries in file_managed

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

I can set the status value by doing:

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

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

What is the right way to achieve this?

+6
source share
1 answer

I would like to create an instance of a file object manually and use file_save() to commit it (e.g. using an image file):

 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); 

Then you must call file_usage_add() so that Drupal knows that your module has an interest in this file (using nid from your $node ):

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

Finally, you can add the file to node:

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

Hope that helps

+14
source

Source: https://habr.com/ru/post/900468/


All Articles