Drupal - How to pass data between operations of a single Batch?
Thanks David for your answer. But unfortunately $context['sandbox']
values were not retained through operations - they were retained through iterations of the same operation but not between operations.
Interestingly though, I found that $context['results']
values were retained between each operation.
I did a simple test using the following module:
<?php
function mytest_menu() {
$items = array();
$items['admin/content/mytest'] = array(
'title' => 'mytest',
'page callback' => 'drupal_get_form',
'page arguments' => array('mytest_form'),
'access arguments' => array('administer content'),
'type' => MENU_NORMAL_ITEM,
);
return $items;
}
function mytest_form() {
$form = array();
$form['submit'] = array(
'#type' => 'submit',
'#value' => t('Submit'),
);
return $form;
}
function mytest_form_submit($form, $form_state) {
$batch = array(
'title' => t('Working ...'),
'operations' => array(),
'finished' => 'mytest_batch_finished',
'init_message' => t('Starting ...'),
'progress_message' => t('Processed @current out of @total.'),
'error_message' => t('An error occurred during processing'),
'progressive' => FALSE
);
$batch['operations'][] = array('mytest_initialize', array('test data'));
$batch['operations'][] = array('mytest_perform', array('different data'));
$batch['operations'][] = array('mytest_perform', array('different data'));
$batch['operations'][] = array('mytest_perform', array('different data'));
batch_set($batch);
batch_process('admin/content/mytest');
}
function mytest_initialize($d, &$context) {
dsm($d);
$context['results']['test'] = 'inti val';
$context['test']['test'] = 'init val';
}
function mytest_perform ($d, &$context) {
dsm($context);
$context['results']['test'] = uniqid();
$context['test']['test'] = $context['results']['test'];
}
function mytest_batch_finished($success, $results, $operations) {
dsm($results);
}
After the batch finished, I could see the dsm()
'd messages. voilà: values were retained.
http://i.stack.imgur.com/tkAXx.png
It seems like only $context['results'] was given to the next operation. Arbitrary keys ($context['my own key']
for example) didn't work.
Hope someone will find this useful :)
PS: *previous not previos (screenshot).