跳转到主要内容
learningxm 提交于 4 September 2013

原文链接:Automatically adding paid membership products based on field values with Ubercart and Content Profile

Ubercart自定义rules实现添加产品到购物车的功能模块

<?php

/**
 * @file
 * This file contains the Rules hooks and functions necessary to enable adding
 * products to carts from Rule actions.
 */

/**
 * Implements hook_rules_action_info().
 */
function mycustommodule_rules_action_info() {

  $actions['mycustommodule_add_product'] = array(
    'label' => t('Add a product to the cart'),
    'group' => t('MyCustomModule Order'),
    'base' => 'mycustommodule_add_product_to_cart',
    'parameter' => array(    
      'product' => array(
        'type' => 'text',
        'label' => t('Product'),
        'restriction' => 'input',
        'options list' => 'mycustommodule_product_list_options',
      ),
      'quantity' => array(
        'type' => 'text',
        'label' => t('Quantity'),
      ),
    ),
  );

  return $actions;
}

/* * ****************************************************************************
 * Condition Callbacks and Forms                                              *
 * **************************************************************************** */

/**
 * Return a list of product nodes, keyed to their nid.
 */
function mycustommodule_product_list_options() {
  // Get a list of all products
  $query = db_select('node', 'n')
    ->fields('n', array('nid', 'title'))
    ->orderBy('title');
  $query->join('uc_products', 'p', 'n.vid = p.vid');

  $result = $query->execute();

  foreach($result as $row) {
    $return[$row->nid] = $row->title;
  }

  return $return;

}

/**
 * Add a product to the user's cart, based on the rule.
 * 
 * @param int $product
 *   nid of the product to add
 * @param nid $quantity 
 *  quanity of product to add
 */
function mycustommodule_add_product_to_cart($product, $quantity = 1) {
  uc_cart_add_item($product, $quantity);
}
?>
Drupal 版本