Skip to main content

How to import node form csv file in drupal7?

Here, I want to import user from csv file in drupal 7 site.

Let's create a custom module and name the module as "csv_import".

csv_import.info
 
   name = Csv Import
   description = Import node from csv file.
   core = 7.x
   package = Hsk

csv_import.module

<?php

/**
 * Implements hook_permission()
 */
function csv_import_permission() {
  return array(
    'administer uploader' => array(
      'title' => t('Administer Uploader'),
      'description' => t('Allow the following roles to upload csv files to the server.'),
    ),
  );
}

/**
 * Implements hook_menu()
 */
function csv_import_menu() {
  $items['file-uploader'] = array(
    'title' => 'Upload a File',
    'type' => MENU_CALLBACK,
    'description' => 'Import a csv',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('csv_import_import_form'),
    'access arguments' => array('administer uploader'),
  );
  return $items;
}

/**
 * Builds a form that will allow users to upload csv files
 *
 * @see
 *   hook_menu()
 */
function csv_import_import_form($form, $form_state) {

  $form['notes'] = array(
    '#type' => 'markup',
    '#markup' => '<div class="import-notes">A few notes when uploading. <ul><li>Make sure the file is in a .csv format.</li><li>Columns should be in *this* order</li><li>Be sure to click the "Upload" button when you select a csv.</li></ul></div>',
    '#upload_location' => 'public://tmp/',
  );

  $form['import'] = array(
    '#title' => t('Import'),
    '#type' => 'managed_file',
    '#description' => t('The uploaded csv will be imported and temporarily saved.'),
    '#upload_location' => 'public://tmp/',
    '#upload_validators' => array(
      'file_validate_extensions' => array('csv'),
    ),
  );

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

/**
 * Submit handler for csv_import_import_form()
 */
function csv_import_import_form_submit($form, $form_state) {
  // Check to make sure that the file was uploaded to the server properly
  $uri = db_query("SELECT uri FROM {file_managed} WHERE fid = :fid", array(
    ':fid' => $form_state['input']['import']['fid'],
  ))->fetchField();
  if(!empty($uri)) {
    if(file_exists(drupal_realpath($uri))) {
      // Open the csv
      $handle = fopen(drupal_realpath($uri), "r");
      // Go through each row in the csv and run a function on it. In this case we are parsing by '|' (pipe) characters.
      // If you want commas are any other character, replace the pipe with it.
      while (($data = fgetcsv($handle, 0, '|', '"')) !== FALSE) {
        $operations[] = array(
          'csv_import_import_batch_processing',  // The function to run on each row
          array($data),  // The row in the csv
        );
      }

      // Once everything is gathered and ready to be processed... well... process it!
      $batch = array(
        'title' => t('Importing CSV...'),
        'operations' => $operations,  // Runs all of the queued processes from the while loop above.
        'finished' => 'csv_import_import_finished', // Function to run when the import is successful
        'error_message' => t('The installation has encountered an error.'),
        'progress_message' => t('Imported @current of @total products.'),
      );
      batch_set($batch);
      fclose($handle);  
    }
  }
  else {
    drupal_set_message(t('There was an error uploading your file. Please contact a System administator.'), 'error');
  }
}

/**
 * This function runs the batch processing and creates nodes with then given information
 * @see
 * csv_import_import_form_submit()
 */
function csv_import_import_batch_processing($data) {
  // Lets make the variables more readable.
  $title = $data[0];
  $body = $data[1];
  $serial_num = $data[2];
  // Find out if the node already exists by looking up its serial number. Each serial number should be unique. You can use whatever you want.
  $nid = db_query("SELECT DISTINCT n.nid FROM {node} n " .
    "INNER JOIN {field_data_field_serial_number} s ON s.revision_id = n.vid AND s.entity_id = n.nid " .
    "WHERE field_serial_number_value = :serial", array(
      ':serial' => $serial_num,
    ))->fetchField();
  if(!empty($nid)) {
    // The node exists! Load it.
    $node = node_load($nid);

    // Change the values. No need to update the serial number though.
    $node->title = $title;
    $node->body['und'][0]['value'] = $body;
    $node->body['und'][0]['safe_value'] = check_plain($body);
    node_save($node);
  }
  else {
    // The node does not exist! Create it.
    global $user;
    $node = new StdClass();
    $node->type = 'page'; // Choose your type
    $node->status = 1; // Sets to published automatically, 0 will be unpublished
    $node->title = $title;
    $node->uid = $user->uid;
    $node->body['und'][0]['value'] = $body;
    $node->body['und'][0]['safe_value'] = check_plain($body);
    $node->language = 'und';

    $node->field_serial_number['und'][0]['value'] = $serial_num;
    $node->field_serial_number['und'][0]['safe_value'] = check_plain($serial_num);
    node_save($node);
  }
}

/**
 * This function runs when the batch processing is complete
 *
 * @see
 * csv_import_import_form_submit()
 */
function csv_import_import_finished() {
  drupal_set_message(t('Import Completed Successfully'));
}

Comments

Popular posts from this blog

How to configure memcache with drupal 8 on ubuntu for reduce page load?

Memcache is an in-memory (RAM). It store data in Key-Value Format. Memcached server automatically stores all the content (data) in allocated RAM on the server. After configure memcache, it increase Drupal Site performance by moving standard caches out of the database. Drupal does not come with memcache by default if we want to install it then we have to install it on server. There are many steps that how to install memcache on the server and how to configure it with drupal 8 for reducing the load on the database with every page request. Step1 :- Open terminal of your machine and run following commands :- a. sudo apt-get update b. sudo apt install memcached c. sudo apt install php-memcached Step2 :- Check that Memcache daemon is working by using the following command : a. "ps aus | grep memcached" Step3 :- Also, check Memcache extension is configured in PHP. For that you have create a file phpinfo.php then write below code. <?php phpinfo(); ?> or sudo vi /var/www/html...

How deploy your angular project on GitHub Pages

Step 1:- Create Repository on github Note :- Open terminal and goto your project direcoty then run following command which you got after created repository. Step 2:- git init Step 3:- git add . Step 4:- git commit -m "first commit" Step 5:- git branch -M main Step 6:- git remote add origin https://github.com/rahuldrupal5788/DevR9angular.git Step 7:- git push -u origin main Step 8:- We need to build our code in production mode for that we will create deployment files that will be deployed on GitHub Pages. By default, this deployment code is generated in the /dist/<ProdectName> folder under the angular project folder, but we need to generate this in the "docs" folder under the angular project folder. So, we need to make a small change in the angular.json file and change the outputpath value to "docs/". Step 9:- Run the following command with the baseHref  option in the git bash window to generate deployment files in the docs folder. ng build --prod --b...

What is Docker? How to create Dockerfile, Volumes? How to manage container with Port Mapping?

What is Docker? Docker is an open source centerlized Platform designed to Create, Deploy and run applications. Docker use container on the host OS to run applications. It allows application to use the same linux Kernal as a System on the host computer, rather than creating a whole virtual OS. We can install docker on any OS but Docker engine run natively on linux distribution. Docker written in 'go' language. Docker is a tool that perform OS level virtualization, also known as Containerization. Before Docker, many users faces the problem that a particular Code is running in  the developer's system but not in the User's System. Docker was first Release in March 2013. It is developed by Soloman Hykes and Sebastion Pahl. Docker is a set of Platform as a service that uses OS level Virtualization whereas VMware uses Hardware level Virtualization. We can say that Docker is a tools which create the VM. Advantages of Docker :- There are following advantage of Docker : No pre-a...