Handling file in Drupal
2011 10 Sep

Handling files with Drupal (CSV import)

Drupal allows pretty smooth file management API for developers. Here is a small piece of code where I tried to import the contents of an uploaded CSV file into the database in Drupal.

  1. Create a menu item for your file upload form
  2. Define the callback for the menu item and make sure to set the form encoding
  3. Make sure that the file imported is of CSV type (check the mime type of the file uploaded)
  4. And finally, get data from the CSV And TA-DA :-)

 

  1. Create a menu item for your file upload form
    function example_menu() { 
    $items = array(); 
    $items['admin/example/import'] = array(
      'title' => 'Import', 
      'page callback' => 'drupal_get_form', 
      'page arguments' => array('example_form'), 
      'access arguments' => array('allow example import'), 
      'type' => MENU_LOCAL_TASK, 
    ); 
    return $items; 
    }

     

  2. Define the callback for the menu item and make sure to set the form encoding
    function example_form() { 
    
      $form = array(); 
      $form['browser'] = array(
        '#type' => 'fieldset', 
        '#title' => t('Browser Upload'), 
        '#collapsible' => TRUE, 
        '#description' => t("Upload a CSV file."), 
      ); 
      $file_size = t('Maximum file size: !size MB.', array('!size' => file_upload_max_size()));
      $form['browser']['file_upload'] = array( 
        '#type' => 'file', 
        '#title' => t('CSV File'), 
        '#size' => 40, 
        '#description' => t('Select the CSV file to be imported. ') . $file_size
      ); 
      $form['submit'] = array( '#type' => 'submit', '#value' => t('Save'), ); 
      // set the form encoding type 
      $form['#attributes']['enctype'] = "multipart/form-data"; 
      return $form; 
    }

     

  3. Make sure that the file imported is of CSV type (check the mime type of the file uploaded)
    function example_form_validate($form, &$form_state) { 
      // attempt to save the uploaded file 
      $file = file_save_upload('file_upload'); 
      // check file uploaded OK 
      if (!$file) { 
        form_set_error('file_upload', t('A file must be uploaded or selected from FTP updates.')); 
      } 
      else if($file->filemime != 'text/csv') { 
        form_set_error('file_upload', t('The file must be of CSV type only.')); 
      } 
      else { 
      // set files to form_state, to process when form is submitted 
        $form_state['values']['file_upload'] = $file; 
      } 
    }

     

  4. And finally, get data from the CSV
    function example_form_submit($form, &$form_state) {
      $line_max = variable_get('user_import_line_max', 1000);
      ini_set('auto_detect_line_endings', true);
      $filepath = $form_state['values']['file_upload']->filepath;
      $handle = @fopen($filepath, "r");
      // start count of imports for this upload
      $send_counter = 0;
      while ($row = fgetcsv($handle, $line_max, ',')) {
      // $row is an array of elements in each row
      // e.g. if the first column is the email address of the user, try something like
        $mail = $row[0];
      }
    }

     

And TA-DA :-) This is a very simple example of how to write code to import content using CSV. File handling APIs are much better in Drupal 7, will post about the same when we get a chance.

Latest Blogs

Digital Public Goods Alliance Strategy 2021–2026

Boosting Digital Infrastructure with Digital Public Goods

The United Nations (UN) defines a roadmap for Digital Public Goods (DPGs) as open-source software, open data, open AI models, open standards, and open content.

Read More

Best Practices for Software Testing

Power of Software Testing: Why Software Teams Use It Effectively

In the modern digital era, where software is used in nearly every aspect of everyday life, the importance of software testing cannot be emphasized.

Read More

Benefits of Programmatic SEO Implementation

What It Is and How to Implement It How SEOs Make the Web Better

In the rapidly evolving field of SEO, staying ahead of the curve necessitates adopting new strategies and utilizing technology.

Read More

Unlocking the potential of SEO for boosting business

Branding With SEO: Boost brand Visibility, credibility, and Engagement With An SEO Strategy

Many people think that the primary function of search engine optimization is to garner organic traffic on a website; however, it is beyond that.

Read More