I wish to add a file in the filesystem to file_managed (if its not already there), so that it can then be attached to a field.
file_save() can be used, but one needs to check if the file is already in file_managed, otherwise file_save() will blow up :
PDOException: SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry 'public://myfile.jpg' for key 'uri': INSERT INTO {file_managed} (uid ...
The first idea was to use file_load() and if that returns false, then do file_save(). But file_load() searches by fid, and we dont yet have that.
$picturepath='iamges';
$file = new stdClass();
$file->uid = $node->uid;
$file->filename = 'myfile.jpg';
$file->uri = file_build_uri($picturepath);
$file->filemime = file_get_mimetype('/var/www/sites/default/files/' . $picturepath);
$file->status = '1';
$savedFile=file_load($file); <<== Always is false
if (!$savedFile) {
dpm('File not yet in db, so file_save');
//$savedFile = file_save($file); <<== blows up on the second run. Website crashes.
}else{
dpm('We already have the file registered in the DB');
// now attach the image to the field in our node
$newnode->field_ideaimage['und'][0] = $savedFile;
field_attache_update('node' $newnode);
}
Thanks in advance for any tips...
Comments
Comment #1
dpovshed commentedHey boran!
What you need to use here is the code fragment like:
Hope this helps, let me know if you need any further assistance!
Comment #2
boran commentedExcellent tip. Thanks a million.