I create a filefield on a content type and set its path settings to, say, 'foo/bar'.

I then use node_save() to save a node of this type, specifying an array of file data.

Because a node of this type with this filefield has never been saved in the UI, the folder does not exist, and my call to file_save_data() prior to node_save() fails.

Comments

quicksketch’s picture

Category: bug » support
Priority: Major » Normal

I don't think this is the case. node_save() should work perfectly fine as long as there is a File FID in the files that are specified in the node. Note that node_save() will *not* automatically upload or save a file for you (since there's nothing in the $_FILES array). You need to use field_file_save() manually before the node_save() call, then use the resulting $file object and put it into the $node->field_[field_name] array of files.

joachim’s picture

Absolutely -- I am saving the file myself, thus:

    $file['filepath'] = filefield_widget_file_path($field) . '/' . $file['filename'];
    $filepath = file_save_data($this->file_data, $file['filepath'], FILE_EXISTS_REPLACE);
    $file['filepath'] = $filepath;
    
    // Write record in files table.
    $file['fid'] = $this->id_local;
    drupal_write_record('files', $file, array('fid'));

I've snipped out the non-relevant bits; the node is saved at a later point with the $fid that gets set in $file.

Basically, if no nodes of this type have been saved in the UI yet, it fails. If one has, it works. The reason appears to be that the folder does not exist yet.

quicksketch’s picture

Basically, if no nodes of this type have been saved in the UI yet, it fails. If one has, it works. The reason appears to be that the folder does not exist yet.

Right, so you should check that the directory exists before trying to save the file. This doesn't have anything to do with node_save(). FileField provides the convenience function field_file_check_directory() to do this for you. Use that function before trying to save the file to ensure that the directory exists and is writable.

joachim’s picture

Status: Active » Fixed

Ok will do. Thanks for your help!

Status: Fixed » Closed (fixed)

Automatically closed -- issue fixed for 2 weeks with no activity.

glacialheart’s picture

field_file_check_directory()

Does that function exist? I can't find it in the API.

http://api.drupal.org/api/search/6/field_file_check_directory

joachim’s picture

It's in this module rather than core: http://api.lullabot.com/field_file_check_directory