I'm using hook_node_presave()
to set values for fields that were left empty when a node is created/updated. Text fields are easy enough ($node->field_name['und'][0]['value'] = 'Default text'
), but image fields have got me stumped...
Image fields have lots of array values (e.g. fid, width, height, alt, etc.). I'm assuming there's a function I can call that'll create all the necessary values, but I can't seem to find it.
On top of all that, I have an external image URL that I'd like to programatically download and save to the image field. I'm using the Filefield Sources module to do this in the interface, but again, I need to know how to do this programatically instead.
I think I found the solution:
file_get_contents()
will allow you to 'download' a file from a URL. Passing the return value of this tofile_save_data()
will allow you to then save the file in Backdrop such that it has a File ID (fid
), etc. Setting thefid
value of the image field seems to then save it to the field in the same way as if you'd uploaded it manually.Here's the working code I'm using: