Removing file from form breaks site I created a module that hooks into the admin menu and allows you to upload a specific file for the site to use.

It allows you to upload a file, and change a file, but as soon as you remove a file and click submit I get the error:


  PDOException: SQLSTATE[23000]: Integrity constraint violation: 1062
  Duplicate entry '' for key 'uri': INSERT INTO {file_managed}
  (filesize, status, timestamp) VALUES (:db_insert_placeholder_0,
  :db_insert_placeholder_1, :db_insert_placeholder_2); Array (
  [:db_insert_placeholder_0] => 0 [:db_insert_placeholder_1] => 1
  [:db_insert_placeholder_2] => 1412011464 ) in drupal_write_record()
  (line 7202 of /var/www/html/includes/common.inc).


I think Im missing a step when it comes to managing files in a form. Here is the relevant module code:

function read_more_news_admin_form($form, &amp;$form_state) {

    $form = array();    

    // File selection form element
    $form['csv_file'] = array(
        '#name' =&gt; 'file',
        '#type' =&gt; 'managed_file',
        '#title' =&gt; t('Choose a CSV File'),
        '#description' =&gt; t('Upload your Daily Nav CSV here'),
        '#upload_location' =&gt; 'public://',
        '#default_value' =&gt; variable_get('csv_fid', ''),
        '#upload_validators' =&gt; array(
            'file_validate_extensions'=&gt; array('csv'),
        ),
    );


    $form['submit'] = array('#type' =&gt; 'submit', '#value' =&gt; t('Submit'));
    return $form;
}

function read_more_news_admin_form_submit(&amp;$form, &amp;$form_state) {

    // Saving the file, setting it to a permanent state, setting a FID variable
    $file = file_load($form_state['values']['csv_file']);
    $file-&gt;status = FILE_STATUS_PERMANENT;
    file_save($file);
    variable_set('csv_fid', $file-&gt;fid);

}
The value of $form_state['values']['csv_file'] is empty (0) when you remove the file. You need to do a sanity check on $file after file_load not only for that reason but also as a good coding practice.

function custom_admin_form_submit(&amp;$form, &amp;$form_state) {
  // Saving the file, setting it to a permanent state, setting a FID variable
  $file = file_load($form_state['values']['csv_file']);
  if ($file) {
    $file-&gt;status = FILE_STATUS_PERMANENT;
    file_save($file);
    variable_set('csv_fid', $file-&gt;fid);
  }
  else {
    variable_set('csv_fid', '');
  }
}