Skip to main content

Create batch process on form submit in Drupal 7

Using Drupal batch API we can create batch processes.


// form submit.
function product_display_submit($form, &$form_state) {

  $products = $form_state['input']['product_table'];

  if (!empty($products)) {
    // Remove empty values.
    $emptyRemoved = remove_empty($products);
    // re-index array.
    $myarray = array_values($emptyRemoved);


    $progress = 0; // where to start
    $max = count($myarray); // how many records to process until stop.

    // Tell Drupal about the batch process.
    $batch = array(
      'operations' => array(),
      'finished' => 'product_display_batch_finished', // runs after batch is finished
      'title' => t('Deleting products'),
      'init_message' => t('Beginning product delete'),
      'progress_message' => t('Deleted @current out of @total'),
      'error_message' => t('Product deletion failed.'),
    );

    // set batch operation.
    $batch['operations'][] = array('product_display_delete_process', array($progress, $max, $myarray));
    batch_set($batch);
  }

}

function product_display_delete_process($progress, $max, $products, &$context) {

  for ($i=$progress; $i < $max; $i++) {
    // Update our progress information.
    $context['message'] = t('Now processing product id #%product_id', array('%product_id' => $products[$i]));

      // $result = commerce_product_delete_multiple($products);
      $result = commerce_product_delete($products[$i]);

      // Delete product display.
      $query = new EntityFieldQuery;

      $query->entityCondition('entity_type', 'node', '=')
      ->propertyCondition('type', 'product_display')
      ->fieldCondition('field_product', 'product_id', $products[$i], '=')
      ->range(0, 1);
      $result = $query->execute();

      if (!empty($result['node'])) {
        // Delete Product Display node.
        foreach ($result['node'] as $nid => $val) break;
        try {
          node_delete($nid);

          // Delete alias.
          $path = path_load(
            array('source' => 'node/' . $key)
          );

          path_delete($path['pid']);
        }
        catch (Exception $e) {
          drupal_set_message('Error occurred. Check logs.');
        }
      }
  }

}

function product_display_batch_finished($success, $results, $operations) {
  if ($success) {
    drupal_set_message('Product deletion is complete');
  }
  else {
    $error_operation = reset($operations);
    watchdog('products_batchprocess_error',t('An error occurred while processing @operation with arguments : @args', array('@operation' => $error_operation[0], '@args' => print_r($error_operation[0], TRUE))));
    $message = t('An error occurred while processing %error_operation with arguments: @arguments', array(
      '%error_operation' => $error_operation[0],
      '@arguments' => print_r($error_operation[1], TRUE)
    ));
    drupal_set_message($message, 'error');
  }
}



References:
https://www.drupal.org/docs/7/api/batch-api/overview
http://hardcoredev.com/blog/using-batch-api-in-drupal-7-tutorial-in-simple-code/
https://rootid.in/think/least-you-need-know-drupal-batch-api-or-how-use-drupal-progress-bar



Comments

Popular posts from this blog

Use Case Diagram for Online Book Store

Online Movie Ticket Booking Sequence Diagram

Linear search & Binary search using Template

Write a program to search an element from a list. Give user the option to perform Linear or Binary search. Use Template functions. #include<iostream> using namespace std; template <class T> void Lsearch(T *a, T item, int n) { int z=0; for(int i=0;i<n;i++) { if(a[i]== item) { z=1; cout<<"\n Item found at position = "<<i+1<<"\n\n"; } else if(z!=1) { z=0; } } if(z==0) cout<<"\n Item not found in the list\n\n"; } template <class T> void Bsearch(T *a, T item, int n) { int beg=0,end=n-1; int mid=beg+end/2; while((a[mid]!=item) && (n>0)) { if(item>a[mid]) beg=mid; else end=mid; mid=(beg+end)/2; n--; } if(a[mid]==item) cout<<"\n Item found at position = "<<mid+1<<"\n\n"; else cout<<"\n Item not found in the list\n\n"; } void main() { int iarr[10] = {2,42,56,86,87,99,323,546,767,886};