Batch operations


Functions

 batch_set ($batch_definition)
 batch_process ($redirect=NULL, $url=NULL)
batch_get ()

Detailed Description

End of "defgroup form_api".

Functions allowing forms processing to be spread out over several page requests, thus ensuring that the processing does not get interrupted because of a PHP timeout, while allowing the user to receive feedback on the progress of the ongoing operations.

The API is primarily designed to integrate nicely with the Form API workflow, but can also be used by non-FAPI scripts (like update.php) or even simple page callbacks (which should probably be used sparingly).

Example:

 $batch = array(
   'title' => t('Exporting'),
   'operations' => array(
     array('my_function_1', array($account->uid, 'story')),
     array('my_function_2', array()),
   ),
   'finished' => 'my_finished_callback',
 );
 batch_set($batch);
 // only needed if not inside a form _submit handler :
 batch_process();

Sample batch operations:

 // Simple and artificial: load a node of a given type for a given user
 function my_function_1($uid, $type, &$context) {
   // The $context array gathers batch context information about the execution (read),
   // as well as 'return values' for the current operation (write)
   // The following keys are provided :
   // 'results' (read / write): The array of results gathered so far by
   //   the batch processing, for the current operation to append its own.
   // 'message' (write): A text message displayed in the progress page.
   // The following keys allow for multi-step operations :
   // 'sandbox' (read / write): An array that can be freely used to
   //   store persistent data between iterations. It is recommended to
   //   use this instead of $_SESSION, which is unsafe if the user
   //   continues browsing in a separate window while the batch is processing.
   // 'finished' (write): A float number between 0 and 1 informing
   //   the processing engine of the completion level for the operation.
   //   1 (or no value explicitly set) means the operation is finished
   //   and the batch processing can continue to the next operation.

   $node = node_load(array('uid' => $uid, 'type' => $type));
   $context['results'][] = $node->nid . ' : ' . $node->title;
   $context['message'] = $node->title;
 }

 // More advanced example: multi-step operation - load all nodes, five by five
 function my_function_2(&$context) {
   if (empty($context['sandbox'])) {
     $context['sandbox']['progress'] = 0;
     $context['sandbox']['current_node'] = 0;
     $context['sandbox']['max'] = db_result(db_query('SELECT COUNT(DISTINCT nid) FROM {node}'));
   }
   $limit = 5;
   $result = db_query_range("SELECT nid FROM {node} WHERE nid > %d ORDER BY nid ASC", $context['sandbox']['current_node'], 0, $limit);
   while ($row = db_fetch_array($result)) {
     $node = node_load($row['nid'], NULL, TRUE);
     $context['results'][] = $node->nid . ' : ' . $node->title;
     $context['sandbox']['progress']++;
     $context['sandbox']['current_node'] = $node->nid;
     $context['message'] = $node->title;
   }
   if ($context['sandbox']['progress'] != $context['sandbox']['max']) {
     $context['finished'] = $context['sandbox']['progress'] / $context['sandbox']['max'];
   }
 }

Sample 'finished' callback:

 function batch_test_finished($success, $results, $operations) {
   if ($success) {
     $message = format_plural(count($results), 'One post processed.', '@count posts processed.');
   }
   else {
     $message = t('Finished with an error.');
   }
   drupal_set_message($message);
   // Providing data for the redirected page is done through $_SESSION.
   foreach ($results as $result) {
     $items[] = t('Loaded node %title.', array('%title' => $result));
   }
   $_SESSION['my_batch_results'] = $items;
 }

Function Documentation

& batch_get (  ) 

batch_process ( redirect = NULL,
url = NULL 
)

Process the batch.

Unless the batch has been marked with 'progressive' = FALSE, the function issues a drupal_goto and thus ends page execution.

This function is not needed in form submit handlers; Form API takes care of batches that were set during form submission.

Parameters:
$redirect (optional) Path to redirect to when the batch has finished processing.
$url (optional - should only be used for separate scripts like update.php) URL of the batch processing page.

Definition at line 2457 of file form.inc.

References $url, _batch_process(), batch_get(), db_last_insert_id(), db_query(), drupal_get_token(), drupal_goto(), get_t(), and url().

Referenced by drupal_process_form(), install_tasks(), and update_batch().

Here is the call graph for this function:

batch_set ( batch_definition  ) 

Open a new batch.

Parameters:
$batch An array defining the batch. The following keys can be used: 'operations': an array of function calls to be performed. Example:
        array(
          array('my_function_1', array($arg1)),
          array('my_function_2', array($arg2_1, $arg2_2)),
        )
All the other values below are optional. batch_init() provides default values for the messages. 'title': title for the progress page. Defaults to t('Processing'). 'init_message': message displayed while the processing is initialized. Defaults to t('Initializing.'). 'progress_message': message displayed while processing the batch. Available placeholders are , , and . Defaults to t('Remaining of .'). 'error_message': message displayed if an error occurred while processing the batch. Defaults to t('An error has occurred.'). 'finished': the name of a function to be executed after the batch has completed. This should be used to perform any result massaging that may be needed, and possibly save data in $_SESSION for display after final page redirection. 'file': the path to the file containing the definitions of the 'operations' and 'finished' functions, for instance if they don't reside in the original '.module' file. The path should be relative to the base_path(), and thus should be built using drupal_get_path().
Operations are added as new batch sets. Batch sets are used to ensure clean code independence, ensuring that several batches submitted by different parts of the code (core / contrib modules) can be processed correctly while not interfering or having to cope with each other. Each batch set gets to specify his own UI messages, operates on its own set of operations and results, and triggers its own 'finished' callback. Batch sets are processed sequentially, with the progress bar starting fresh for every new set.

Definition at line 2399 of file form.inc.

References batch_get(), and get_t().

Referenced by install_tasks(), locale_languages_predefined_form_submit(), node_mass_update(), and update_batch().

Here is the call graph for this function:


Generated on Mon Jun 2 15:08:48 2008 for SimpleTest by  1.5.5