0

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, &$form_state) {

    $form = array();    

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


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

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

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

}
1

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(&$form, &$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->status = FILE_STATUS_PERMANENT;
    file_save($file);
    variable_set('csv_fid', $file->fid);
  }
  else {
    variable_set('csv_fid', '');
  }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.