[Drupal] [Solved] How to use managed_file for uploading private files with its deletion in Drupal

| | 2 min read

Steps to upload private documents to the web page by storing file id in a system variable and delete the file when updating the same with necessary validations in Drupal 7.

While working with a project in Zyxware, I need to create a form for uploading a PDF file as private and option to update it there itself. Steps that I do for this are:

  • Add the document path in 'Private file system path' in the site configuration page
    (ie in, admin/config/media/file-system) as 'sites/default/files/private'.
  • Create a menucallback for the form with following code :
    
      //adding form
      function MODULE_NAME_document_add_form($form, &$form_state) {
        $doc_id = variable_get('document_variable_name');
        $form['doc_file'] = array(
          '#title' => t('Upload the document'),
          '#type' => 'managed_file',
          '#description' => t('Supports only .pdf files'),
          '#upload_location' => 'private://document-folder/',
          '#default_value' => isset($doc_id) ? $doc_id : NULL,
          '#upload_validators' => array(
            'file_validate_extensions' => array('pdf'),
          ),
        );
    
        $form['document_submit'] = array(
          '#type' => 'submit',
          '#value'  => t('Save'),
          '#submit' => array('module_name_document_submit'),
        );
        return $form;
      }
    
      //submission function
      function MODULE_NAME_document_submit($form, $form_state) {
        //updations for light stress relief document
        if (isset($form_state['values']['doc_file'])) {
          //remove existing document while clicking remove button
          if ($form_state['values']['doc_file'] == 0){
            //get existing file id to delete
            $document_exist_id = variable_get('document_variable_name');
            $document_exist_file = file_load($document_exist);
            if (!empty($document_exist_file)) {
              //delete file usage
              file_usage_delete($document_exist_file, 'MODULE_NAME', 'TYPE', $document_exist_id);
              // The file_delete() function takes a file object and checks to see if
              // the file is being used by any other modules. If it is the delete
              // operation is canceled, otherwise the file is deleted.
              file_delete($document_exist_file, TRUE);
              drupal_set_message(t('Old document removed.'));
            }
          }
          else {
            //adding document
            $current_document = file_load($form_state['values']['doc_file']);
            if (!empty($current_document->fid)) {
              //get currently uploaded file id
              $file_id = $current_document->fid;
              //setting file id to its variable
              variable_set('document_variable_name', $file_id);
              file_usage_add($current_document, 'MODULE_NAME', 'TYPE', $file_id);
              //make file status as permanent
              $current_document->status = FILE_STATUS_PERMANENT;
              file_save($current_document);
              drupal_set_message("Documents uploaded successfully.");
            }
          }
        }
      }
    

Please feel free to share your thoughts and doubts regarding this here.