跳转到主要内容
洪文敏 提交于 18 July 2016

使用这个Batch API的原因是,我每天会有几百到一千条布匹记录需要Feeds到我的站点中,Feeds的记录又需要进行按日期和其它的一些字段进行GroupBY归档。所以在使用一般的循环操作时会因为PHP时间超时,造成数据无法完成。为了将数据完整的完成必须要将数据进行分隔处理将大的循环改成多批次小循环,所以就有使用Batch API的原因。

 

下面是我的源码:

<?php

/**
 * @file
 * Defines "一个布匹上传完成后的归档规则" 
 *
 * @TODO: Split admin functions into their own file.
 */
 
 function fabric_archive_menu(){
	 
	$items['warehouse/showbase']=array(
		'title'=>'Fabric Base Archives',
		'description'=>'显示最近上传未归档记录',
		'page callback'=>'drupal_get_form',
		'page arguments'=>array('fabric_base_archive_form'),
		//页面回调的function
		'access arguments'=>array('Fabric Base'),
		//页面调用的用户权限
		'access callback'=>TRUE,
		//'weight'=>'5',
		//'file' => 'sample_barcode.inc',
	
	);	
	return $items;	
}

function fabric_base_archive_form($form, &$form_state){
	
	$form=array();
	$form['fabric']=array(
		'#type' => 'fieldset',
		'#title' => t('Fabric Record  Archive'),
	 );
	$form['fabric']['description']=array(
		 '#type'=>'markup',
		 '#markup' => '<p>' . t('Click the button below to begin.') . '</p>',
		);	
	$form['fabric']['submit']= array(
		'#type' => 'submit',
		'#value' => t('Archive'),			
		);
    $options=fabric_base_archive_mygetviews('fabric_base','block_2');	
    $nid=(count($options));
	
  if (empty($nid)){
	  drupal_set_message(t('You do not currently have any Fabric data,As a result, this form is disabled'));
	  $form['fabric']['submit']['#disabled']=TRUE;
	  
  }
  return $form;
}
function fabric_base_archive_form_submit($form, &$form_state){
	
	$options=fabric_base_archive_mygetviews('fabric_base','block_2');	
    $num_operations=(count($options));
	
	
	$_SESSION['http_request_count'] = 0;
	
	drupal_set_message(t('Created Warehous Table @num Record ',array('@num'=>$num_operations)));
	$i=1;
	foreach($options as $row){	
		//dpm($row);	
		$operations[]=array(
			'fabric_base_archive_op',
			array(
				$row,
				t('(Operation @operation)',array('@operation'=>$i)),
			),		
		);
		$i++;
	}
	$batch=array(
		'operations'=>$operations,
		'finished'=>'fabric_base_archive_finished',		
	);
	batch_set($batch);
}

function fabric_base_archive_op($row,$operation_details,&$context){
	
  $node=fabric_base_warehouse_save($row);
  $returndate=$row->field_field_warehousereturndate[0]['raw']['value'];
  $contract=$row->field_field_warehousecontract[0]['raw']['value'];
  $mercery=$row->field_field_warehousemercery[0]['raw']['value'];
  $styleno=$row->field_field_warehousestyleno[0]['raw']['value'];
  $cylinder=$row->field_field_warehousecylinder[0]['raw']['value'];
  $orderno=$row->field_field_warehouseorderno[0]['raw']['value'];
  $storageno=$row->field_field_warehousestorageno[0]['raw']['value'];
  $colour=$row->field_field_warehousecolour[0]['raw']['value'];
  
 
  $query=db_select('node','n' );
  $query->join('field_data_field_tracerttag','ftag','ftag.entity_id=n.nid');  
  $query->leftjoin('field_data_field_warehousereturndate','fdate','fdate.entity_id=n.nid');
  $query->leftjoin('field_data_field_warehousecontract','fcon','fcon.entity_id=n.nid');
  $query->leftjoin('field_data_field_warehousemercery','fmerc','fmerc.entity_id=n.nid');
  $query->leftjoin('field_data_field_warehousestyleno','fsty','fsty.entity_id=n.nid');
  $query->leftjoin('field_data_field_warehousecylinder','fcyl','fcyl.entity_id=n.nid');
  $query->leftjoin('field_data_field_warehouseorderno','forder','forder.entity_id=n.nid');
  $query->leftjoin('field_data_field_warehousestorageno','fsto','fsto.entity_id=n.nid');
  $query->leftjoin('field_data_field_warehousecolour','fcolo','fcolo.entity_id=n.nid');
  $query->fields('n',array('nid','title'));
  $query->fields('fdate',array('field_warehousereturndate_value'));
  $query->fields('fcon',array('field_warehousecontract_value'));
  $query->fields('fmerc',array('field_warehousemercery_value'));
  $query->fields('fsty',array('field_warehousestyleno_value'));
  $query->fields('fcyl',array('field_warehousecylinder_value'));
  $query->fields('forder',array('field_warehouseorderno_value'));
  $query->fields('fsto',array('field_warehousestorageno_value'));
  $query->fields('fcolo',array('field_warehousecolour_value'));
  $query->condition('n.status','1','=');
  $query->condition('n.type','fabricbase','=');
  $query->condition('ftag.field_tracerttag_value','0','=');
  $query->condition('fdate.field_warehousereturndate_value',db_like($returndate),'LIKE');
  $query->condition('fcon.field_warehousecontract_value',db_like($contract),'LIKE');
  $query->condition('fmerc.field_warehousemercery_value',db_like($mercery),'LIKE');
  $query->condition('fsty.field_warehousestyleno_value',db_like($styleno),'LIKE');
  $query->condition('fcyl.field_warehousecylinder_value',db_like($cylinder),'LIKE');
  $query->condition('forder.field_warehouseorderno_value',db_like($orderno),'LIKE');
  $query->condition('fsto.field_warehousestorageno_value',db_like($storageno),'LIKE');
  $query->condition('fcolo.field_warehousecolour_value',db_like($colour),'LIKE');
  $query->orderBy('n.created','DESC');
  
  $result=$query->execute();
  $i=1;
  foreach ($result as $value){
	  $barcode=fabric_base_barcode_save($value,$node->nid,$i);
	  $node->field_samplegroup['und'][$i-1]['first']=$barcode;
	  $node->field_samplegroup['und'][$i-1]['second']='1';	 
	  $i++;	   
  }
  node_save($node);
  $context['results'][] = $node->nid ;

  // Optional message displayed under the progressbar.
  $context['message'] = t('Create Warehous Table "@title"', array('@title' => $node->nid)) . ' ' . $operation_details;

 _fabric_base_archive_update_http_requests(); 
}
function fabric_base_archive_finished($success, $results, $operations) {
  if ($success) {
    
    drupal_set_message(t('@count results processed in @requests HTTP requests.', array('@count' => count($results), '@requests' => _fabric_base_archive_get_http_requests())));
    drupal_set_message(t('The final result was "%final"', array('%final' => end($results))));
  }
  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),
        )
      ),
      'error'
    );
  }
}

function fabric_base_archive_mygetviews($viewsname,$displayname){
	$views=views_get_view($viewsname);
    $views->preview($displayname);
    $result=$views->result;
	return $result;
}

function fabric_base_warehouse_save($key){
			Global $user;
			
			$node= new stdClass();
			$node->type="warehouse_table";
			node_object_prepare($node); // Sets some defaults. Invokes hook_prepare() and hook_node_prepare().
			$node->uid=$user->uid;			
			$node->changed=$node->created=time();
			$node->sticky=0;
			$node->status=1;
			$node->language='und';
			$node->field_warehousefactory['und'][0]['tid']=$key->field_field_localtion[0]['raw']['tid'];
			$node->field_warehousesupple['und'][0]['value']=$key->field_field_warehousesupple[0]['raw']['value'];
			$node->field_warehousebrand['und'][0]['tid']=$key->field_field_brand[0]['raw']['tid'];
			$node->field_warehousestorageno['und'][0]['value']=$key->field_field_warehousestorageno[0]['raw']['value'];
			$node->field_warehouseorderno['und'][0]['value']=$key->field_field_warehouseorderno[0]['raw']['value'];
			$node->field_warehousemercery['und'][0]['value']=$key->field_field_warehousemercery [0]['raw']['value'];
			$node->field_warehousecolour['und'][0]['value']=$key->field_field_warehousecolour [0]['raw']['value'];
			$node->field_warehousecylinder['und'][0]['value']=$key->field_field_warehousecylinder[0]['raw']['value'];
			$node->field_warehousecontract['und'][0]['value']=$key->field_field_warehousecontract[0]['raw']['value'];
			$node->field_warehousestyleno['und'][0]['value']=$key->field_field_warehousestyleno[0]['raw']['value'];
			$node->field_warehousedescription['und'][0]['value']=$key->field_field_warehousedescription[0]['raw']['value'];
			$node->field_warehouseequalnumber['und'][0]['value']=$key->nid_1;
			$node->field_warehouseyardage['und'][0]['value']=$key->field_field_warehouseyardage[0]['raw']['value'];
			$node->field_warehousereturndate['und'][0]['value']=$key->field_field_warehousereturndate[0]['raw']['value'];			
			$node=node_submit($node);			
			node_save($node);
		    $node->title=$node->nid;
			node_save($node);
			return $node;
 }

 function fabric_base_barcode_save($key,$warehouseid,$i){
	 $node=node_load($key->nid);	
	 $node->title="B".sprintf("%08d",(int)$warehouseid).sprintf("%03d",$i);
	 
	 $node->field_tracerttag['und'][0]['value']='1';
	 $node->field_warehousereference['und'][0]['target_id']=$warehouseid;
	 
	 node_save($node);
	 return $node->title;
 }
 
 function fabric_base_node_insert($node){
	switch($node->type){
		case 'warehouse_table':
			db_update('node')
				->fields(array('title'=>$node->nid,))
				->condition('nid',$node->nid,'=')
				->execute();				
		break;
		default:break;
	}
	
}
 
 /**
 * Utility function to increment HTTP requests in a session variable.
 */
function _fabric_base_archive_update_http_requests() {
  $_SESSION['http_request_count']++;
}

/**
 * Utility function to count the HTTP requests in a session variable.
 * 
 * @return int
 *   Number of requests.
 */
function _fabric_base_archive_get_http_requests() {
  return !empty($_SESSION['http_request_count']) ? $_SESSION['http_request_count'] : 0;
}
/**
 * @} End of "defgroup batch_example".
 */


 

标签
Drupal 版本