I have a custom module with a form. That form has a managed_file form element.

<?php
        $form
['other']['file'] = array(
           
'#type' => 'managed_file',
           
'#title' => t('Upload Image'),
           
'#description' => t('Images must be one of jpg, bmp, gif or png formats.'),   
           
'#upload_validators' => array(
               
'file_validate_extensions' => array('gif png jpg jpeg'),
               
'file_validate_size' => array(2*1048576),
            ),
        );
?>

The file is passed through in the form_state['values'], but I just cannot figure out how to properly save the file so that Drupal can reference it and attach it to the node I'm creating. I may not be using file_usage_add properly, but I've tried it in 10 different ways and still no luck.

<?php
    $node_story
= new stdClass();
   
$node_story->title = $form_state['values']['first_name'] . ' ' . $form_state['values']['last_name'];
   
$node_story->type = "story";
   
$node_story->language = LANGUAGE_NONE;
   
$node_story->created = date('U');
   
$node_story->changed = $node_story->created;
   
$node_story->promote = 0; // Display on front page ? 1 : 0
   
$node_story->sticky = 0// Display top of page ? 1 : 0
   
$node_story->status = 0;   // Published ? 1 : 0
   
$node_story->uid = 0;

   
// ------------------------------------ //
   
   
$node_story->body[$node_story->language][0]['value'] = $form_state['values']['story'];
   
$node_story->field_story_first_name[$node_story->language][0]['value'] = $form_state['values']['first_name'];
   
$node_story->field_story_last_name[$node_story->language][0]['value'] = $form_state['values']['last_name'];

   
// Load the file via file.fid.
   
$file = file_load($form_state['values']['file']);
   
// Change status to permanent.
   
$file->status = FILE_STATUS_PERMANENT;
   
// Save.
   
file_save($file);
   
// Attach to node
   
$node_story->field_story_image[$node_story->language][0] = $file;

    if(
$node_story = node_submit($node_story)) {
       
node_save($node_story);
    }

   
// Record that the module (in this example, user module) is using the file.
   
file_usage_add($file, 'jxstories', 'node', $node_story->nid);  // this module is called jxstories
?>

If anyone can help solve this little mystery with me I would be very happy. Thanks.

Comments

I keep getting... The file

I keep getting...

The file used in the Upload Image field may not be referenced.

I know I'm close, but I can't quite get it.

Seems as though I don't need

Seems as though I don't need file_usage_add(). Perhaps I was mistaken. Seems to be working now without it.