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

Main menu dropdown parent item clickable in Drupal 8 using Bootstrap 4

 Edit menu--main.html.twig template file {# /**  * @file  * Bootstrap Barrio's override to display a menu.  *  * Available variables:  * - menu_name: The machine name of the menu.  * - items: A nested list of menu items. Each menu item contains:  *   - attributes: HTML attributes for the menu item.  *   - below: The menu item child items.  *   - title: The menu link title.  *   - url: The menu link url, instance of \Drupal\Core\Url  *   - localized_options: Menu link localized options.  *   - is_expanded: TRUE if the link has visible children within the current  *     menu tree.  *   - is_collapsed: TRUE if the link has children within the current menu tree  *     that are not currently visible.  *   - in_active_trail: TRUE if the link is in the active trail.  */ #} {% import _self as menus...

Add JS to the bottom of the page in Drupal 7

How to add JS at bottom of a particular page in Drupal 7 Step 1: Get the page id. In case of front page "is_front"  Step 2: In template.php file of your theme add the below code : function illume_preprocess_page(&$variables) { if ($variables['is_front']) { drupal_add_js(path_to_theme().'/js/util.js', array('type' => 'file', 'scope' => 'footer')); drupal_add_js(path_to_theme().'/js/main.js', array('type' => 'file', 'scope' => 'footer')); drupal_add_js(path_to_theme().'/js/slideimage.js', array('type' => 'file', 'scope' => 'footer')); $variables['bottom_scripts'] = drupal_get_js(); } } This way you can add JS file using drupal_add_js() and define scope as footer. Step 3: Now you can use bottom_script variable to the page tpl file where you want to add JS print $bottom_scripts;

Use Case Diagram for Online Book Store