0

I'm trying to create a batch to import users. I used this (http://pastebin.com/duTbxpgd) as an example, but somehow it's not working. I see the progress bar advancing and It's showing the right number of rows I'm processing. But what I'm trying to do in the operation function isn't executed.

Here's my code:

function form_submit($form, &$form_state) {
  batch_import_users();
}

function batch_import_users() {
  db_set_active('mysqldb');

  $result = db_query("SELECT * FROM {users}");

  db_set_active('default');

  $batch = array(
    'title' => t('Importing users ...'),
    'operations' => array(),
    'init_message' => t('Commencing'),
    'progress_message' => t('Processed @current out of @total.'),
    'error_message' => t('An error occurred during processing'),
    'finished' => 'batch_import_users_finished',
    'progressive' => FALSE,
    'file' => 'users.inc',
  );

  foreach ($result as $row) {
    $batch['operations'][] = array('batch_create_user', array($row));
  }

  batch_set($batch);

  batch_process();
}

function batch_create_user($row, &$context) {
  // Here I'm just trying to get some output so I know the operation is called, I'm not actually importing the users yet.

  drupal_set_message($row->uid . ' : ' . $row->login);
  dd($row->uid . ' : ' . $row->login);

  $context['results']['processed']++;
  $context['message'] = $row->login;
}

function batch_import_users_finished($success, $results, $operations) {
  if ($success) {
    drupal_set_message('Importing users has finished.');
  }
  else {
    drupal_set_message('Some error.');
  }
}

Am I missing something or doing something wrong? Any help is very much appreciated.

bumped to the homepage by Community yesterday

This question has answers that may be good or bad; the system has marked it active so that they can be reviewed.

  • I don't believe that drupal_set_message will work inside a batch. Have you tried using watchdog instead to log what's happening? – Alfred Armstrong Apr 16 '13 at 8:46
  • Thanks for your response. I tried logging a message with watchdog in the function batch_create_user() but nothing shows up. – Smos Apr 16 '13 at 11:59
0

Try below code

$operations = array();
foreach ($result as $row) {
  $operations[] = array('batch_create_user', array($row));
}

$batch = array(
  'title' => t('Importing users ...'),
  'operations' => $operations,
  'init_message' => t('Commencing'),
  'progress_message' => t('Processed @current out of @total.'),
  'error_message' => t('An error occurred during processing'),
  'finished' => 'batch_import_users_finished',
  'file' => drupal_get_path('module', 'user') . '/' . 'user.inc',
);

Also add path to redirect after batch process

batch_process();

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.