I have a form that works great for adding fields, including and image, to a node and saving it.
I want to allow users to edit their fields and change the data, including their image. I figure there is some way to retrieve and display the current image and then allow the user to upload and save/replace the image with a new one. I can't figure out how to show a preview of the existing image on the Edit form. I assume somewhere I should use File_Exists_Replace, but the rest is an overwhelming mystery.
Here is the code I use for the original form:
$form['logo'] = array(
'#title' => t('Image'),
'#type' => 'managed_file',
'#description' => t('Only image files will be allowed.'),
'#default_value' => variable_get('logo', ''),
'#upload_location' => 'public://misc/media',
'#upload_validators' => array(
'file_validate_extensions' => array('png gif jpg jpeg'),
'file_validate_size' => array(2*1024*1024),
)
);
And the submit function:
// Load the file via file.fid.
$file = file_load($form_state['values']['logo']);
// Change status to permanent.
$file->status = FILE_STATUS_PERMANENT;
// Save.
file_save($file);
// Record that the module (in this example, cformtwo module) is using the file.
file_usage_add($file, 'cformtwo', 'node', 1);
...
node_submit($node);
node_save($node);
I have spent days trying to figure out how to do this.