2012-10-30 7 views
4

처리를 위해 배치 페이지를 설정하려고하는데 예제가 필요합니다. 예제 모듈에있는 예제는 폼 내에 있으며 배치 요청을 처리 할 폼과 독립적으로 실행할 수있는 페이지가 필요합니다. 예를 들어Drupal 7 배치 페이지 예제

: 일괄 처리 기능은 $ 작업의 형태로 다른 함수를 호출 할

function mymodule_batch_2() { 
$operations[] = array('mymodule_onefunction','mymodule_anotherfunction') 
$batch = array(
    'operations' => $operations, 
    'finished' => 'mymodule_finished', 
    // We can define custom messages instead of the default ones. 
    'title' => t('Processing batch 2'), 
    'init_message' => t('Batch 2 is starting.'), 
    'progress_message' => t('Processed @current out of @total.'), 
    'error_message' => t('Batch 2 has encountered an error.'), 
); 
    batch_set($batch); 
    batch_process(''); 
} 

.

+0

제거 batch_process를 (''); – milkovsky

답변

4

작업 할 ID를 배치 프로세스에 제공해야합니다. batch_process ('mybatch') 그렇지 않으면 yourmexample이 올바른 것입니다. 이 전략에 특별한 문제가 있습니까? 여기

+0

제 문제는 포함 경로에없는 개별 파일에서 전체 배치 프로세스를 호출하려고했습니다. 나머지 기능을 호출하기 위해 단순히 mymodule.module 및 parameter >> file <<에 일괄 처리 기능을 추가했습니다. –

+0

또는 배치 정의에 '파일'을 추가 할 수 있습니다 ... drupal_get_path를 사용하여 포함 파일의 전체 경로를 작성하십시오. – Dave

2

당신은 일괄 호출 형태로 배치 relization의 내 샘플을 볼 수 있습니다

function my_module_menu() { 
     $items['admin/commerce/import'] = array(
     'title' => t('Import'), 
     'page callback' => 'drupal_get_form', 
     'page arguments' => array('my_module_settings_form'), 
     'access arguments' => array('administer site settings'), 
     'type' => MENU_NORMAL_ITEM, 
    ); 
     return $items; 
    } 

    /** 
    * Import form 
    */ 
    function my_module_settings_form() { 
     $form = array(); 
     $form['import'] = array(
     '#type' => 'fieldset', 
     '#title' => t('Import'), 
     '#collapsible' => TRUE, 
     '#collapsed' => FALSE, 
    ); 

     $form['import']['submit'] = array(
     '#type' => 'submit', 
     '#value' => t('Import'), 
    ); 
     return $form; 
    } 

    function my_module_settings_form_submit($form, &$form_state) { 
     batch_my_module_import_start(); 
    } 


    /** 
    * Batch start function 
    */ 
    function batch_my_module_import_start() { 

     $batch = array(
     'title' => t('Import products'), 
     'operations' => array(
      array('_batch_my_module_import', array()), 
     ), 
     'progress_message' => t('Import. Operation @current out of @total.'), 
     'error_message' => t('Error!'), 
     'finished' => 'my_module_batch_finished', 
    ); 

     batch_set($batch); 
    } 

    /** 
    * Import from 1C operation. Deletes Products 
    */ 
    function _batch_my_module_import(&$context) { 
     // Your iterms. In my case select all products 
     $pids = db_select('commerce_product', 'p') 
      ->fields('p', array('sku', 'product_id', 'title')) 
      ->condition('p.type', 'product') 
      ->execute() 
      ->fetchAll(); 

     // Get Count of products 
     if (empty($context['sandbox']['progress'])) { 
     $context['sandbox']['progress'] = 0; 
     $context['sandbox']['max'] = count($pids); 
     watchdog('import', 'import products'); 
     } 
     // Create Iteration variable 
     if (empty($context['sandbox']['iteration'])) { 
     $context['sandbox']['iteration'] = 0; 
     } 
     // Check for the end of cycle 
     if ($context['sandbox']['iteration'] < $context['sandbox']['max']) { 
     // Count of operation in one batch step 
     $limit = 10; 
     // Counts completed operations in one batch step 
     $counter = 0; 
     if ($context['sandbox']['progress'] != 0) { 
      $context['sandbox']['iteration'] = $context['sandbox']['iteration'] + $limit; 
     } 
     // Loop all Product items in xml 
     for ($i = $context['sandbox']['iteration']; $i < $context['sandbox']['max'] && $counter < $limit; $i++) { 

      /* Loop items here */ 
      /* ... */ 
      /* ... */ 
      $context['results']['added']['products'][] = $product_item->title; 


      // Update Progress 
      $context['sandbox']['progress']++; 
      $counter++; 
      // Messages 
      $context['message'] = t('Now processing product %name. Product %progress of %count', array('%name' => $product_item->title, '%progress' => $context['sandbox']['progress'], '%count' => $context['sandbox']['max'])); 
      $context['results']['processed'] = $context['sandbox']['progress']; 
     } 
     } 

     if ($context['sandbox']['progress'] != $context['sandbox']['max']) { 
     $context['finished'] = $context['sandbox']['progress']/$context['sandbox']['max']; 
     } 
    } 


/** 
* Finish of batch. Messagess 
*/ 
function my_module_batch_finished($success, $results, $operations) { 
    if ($success) { 
    drupal_set_message(t('@count products added.', array('@count' => isset($results['added']) ? count($results['added']) : 0))); 
    } 
    else { 
    $error_operation = reset($operations); 
    drupal_set_message(t('An error occurred while processing @operation with arguments : @args', array('@operation' => $error_operation[0], '@args' => print_r($error_operation[0], TRUE)))); 
    } 
    watchdog('import', 'import finished'); 
} 
+0

이 페이지가 자동으로 제출됩니까? –

+0

제출 버튼을 눌러야합니다. 자동 제출이란 무엇입니까? 질문에 언급하지 않았습니다. – milkovsky

-1
function module_name_import_form_submit($form, $form_state) { 
    // Check to make sure that the file was uploaded to the server properly 
    $uri = db_query("SELECT uri FROM {file_managed} WHERE fid = :fid", array(
    ':fid' => $form_state['input']['import']['fid'], 
))->fetchField(); 
    if(!empty($uri)) { 
    if(file_exists(drupal_realpath($uri))) { 
     // Open the csv 
     $handle = fopen(drupal_realpath($uri), "r"); 
     // Go through each row in the csv and run a function on it. In this case we are parsing by '|' (pipe) characters. 
     // If you want commas are any other character, replace the pipe with it. 
     while (($data = fgetcsv($handle, 0, '|', '"')) !== FALSE) { 
     $operations[] = array(
      'module_name_import_batch_processing', // The function to run on each row 
      array($data), // The row in the csv 
     ); 
     } 

     // Once everything is gathered and ready to be processed... well... process it! 
     $batch = array(
     'title' => t('Importing CSV...'), 
     'operations' => $operations, // Runs all of the queued processes from the while loop above. 
     'finished' => 'module_name_import_finished', // Function to run when the import is successful 
     'error_message' => t('The installation has encountered an error.'), 
     'progress_message' => t('Imported @current of @total products.'), 
    ); 
     batch_set($batch); 
     fclose($handle);  
    } 
    } 
    else { 
    drupal_set_message(t('There was an error uploading your file. Please contact a System administator.'), 'error'); 
    } 
} 

/** 
* This function runs the batch processing and creates nodes with then given information 
* @see 
* module_name_import_form_submit() 
*/ 
function module_name_import_batch_processing($data) { 
    // Lets make the variables more readable. 
    $title = $data[0]; 
    $body = $data[1]; 
    $serial_num = $data[2]; 
    // Find out if the node already exists by looking up its serial number. Each serial number should be unique. You can use whatever you want. 
    $nid = db_query("SELECT DISTINCT n.nid FROM {node} n " . 
    "INNER JOIN {field_data_field_serial_number} s ON s.revision_id = n.vid AND s.entity_id = n.nid " . 
    "WHERE field_serial_number_value = :serial", array(
     ':serial' => $serial_num, 
    ))->fetchField(); 
    if(!empty($nid)) { 
    // The node exists! Load it. 
    $node = node_load($nid); 

    // Change the values. No need to update the serial number though. 
    $node->title = $title; 
    $node->body['und'][0]['value'] = $body; 
    $node->body['und'][0]['safe_value'] = check_plain($body); 
    node_save($node); 
    } 
    else { 
    // The node does not exist! Create it. 
    global $user; 
    $node = new StdClass(); 
    $node->type = 'page'; // Choose your type 
    $node->status = 1; // Sets to published automatically, 0 will be unpublished 
    $node->title = $title; 
    $node->uid = $user->uid;   
    $node->body['und'][0]['value'] = $body; 
    $node->body['und'][0]['safe_value'] = check_plain($body); 
    $node->language = 'und'; 

    $node->field_serial_number['und'][0]['value'] = $serial_num; 
    $node->field_serial_number['und'][0]['safe_value'] = check_plain($serial_num); 
    node_save($node); 
    } 
} 

/** 
* This function runs when the batch processing is complete 
* 
* @see 
* module_name_import_form_submit() 
*/ 
function module_name_import_finished() { 
    drupal_set_message(t('Import Completed Successfully')); 
} 
+0

다른 사람들이 더 자세한 내용을 묻지 않고도 쉽게 이해할 수 있도록 작업 방법 및 질문에 대한 대답에 대한 자세한 정보 및/또는 설명을 추가해야합니다. 어쨌든, StackOverflow에 오신 것을 환영합니다 :) – koceeng