order_example.module 12 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336
<?php
/**
 * @file order_example.module
 * Demonstrates adding line items to orders, custom order types, etc.
 *
 * The examples are, in order:
 *  - Order creation (using the form provided for this module)
 *  - Simply adding a product to the cart in the most direct way possible.
 *  - Creating a custom order type at module enable time.
 *  - Order states
 *  - Order statuses
 */

/**
 * Implements hook_menu().
 *
 * Simply presents a page that will explain what this module is for.
 * hook_menu() has nothing to do with the checkout page functionality.
 */
function order_example_menu() {
  $items['commerce_examples/order_example'] = array(
    'title' => 'Order Example',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('order_example_info_page'),
    'access callback' => TRUE,
  );
  return $items;
}

/**
 * This form provides a way to interact with some of the example functions
 * provided here.
 */
function order_example_info_page($form, &$form_state) {
  $form['explanation'] = array(
    '#type' => 'item',
    '#markup' => t('This example demonstrates custom order types, programmatically adding a line item to an order, etc.'),
  );

  $form['order_creation'] = array(
    '#type' => 'fieldset',
    '#title' => t('Order creation'),
    '#description' => t('Here we create an order for a user, create a line item with the selected product, and add the line item to the product.')
  );
  $form['order_creation']['account_owning_order'] = array(
    '#type' => 'textfield',
    '#title' => t('User for whom the order will be created'),
    '#autocomplete_path' => 'user/autocomplete',
    '#description' => t('This technique requires a user.'),
    '#default_value' => $GLOBALS['user']->name,
  );
  $form['order_creation']['product_to_add'] = array(
    '#type' => 'textfield',
    '#title' => t('Product to place in the order'),
    // Here we're using Commerce Product's autocomplete path in an unusual way
    // just to get a product for the form.
    '#autocomplete_path' => 'commerce_product/autocomplete/any/any/any',
  );
  $form['order_creation']['use_cart'] = array(
    '#type' => 'checkbox',
    '#title' => t('Add to an existing user cart, if possible (replaces user cart)'),
    '#description' => t('We can either use the existing cart or create a completely new order.')
  );
  $form['order_creation']['order_creation_submit'] = array(
    '#type' => 'submit',
    '#value' => t('Create or update an order with this product'),
    '#submit' => array('order_example_order_creation_submit'),
    '#validate' => array('order_example_order_creation_validate'),
  );

  $form['simple_add_to_cart'] = array(
    '#type' => 'fieldset',
    '#title' => t('Super-simple Add-to-cart'),
    '#description' => t("This version uses the simplified commerce_cart_product_add_by_id() to just add a product by its ID to the current user's cart"),
  );
  $form['simple_add_to_cart']['addcart_product'] = array(
    '#type' => 'textfield',
    '#title' => t('Product to add to cart'),
    // Here we're using Commerce Product's autocomplete path in an unusual way
    // just to get a product for the form.
    '#autocomplete_path' => 'commerce_product/autocomplete/any/any/any',
  );
  $form['simple_add_to_cart']['addcart_submit'] = array(
    '#type' => 'submit',
    '#value' => t('Add this item to cart'),
    '#submit' => array('order_example_add_cart_submit'),
    '#validate' => array('order_example_add_cart_validate'),
  );
  return $form;
}

/**
 * Validation handler for order creation.
 *
 * Convert the SKUs we gathered into product IDs and the usernames into ids.
 *
 * The form value conversion shown here is not part of the core example. It's
 * just a way to make the form do what we want to demonstrate order creation.
 */
function order_example_order_creation_validate($form, &$form_state) {
  $value = array();
  // If a value was entered into the autocomplete...
  if (!empty($form_state['values']['product_to_add'])) {
    order_example_validate_sku($form['order_creation']['product_to_add'], $form_state['values']['product_to_add'], $form_state);
    // Convert the username to a uid.
    $account = user_load_by_name($form_state['values']['account_owning_order']);
    if (!empty($account)) {
      $form_state['values']['account_owning_order'] = $account->uid;
    }
    else {
      form_error($form['order_creation']['account_owning_order'], t('You must supply a valid user to own the account.'));
    }
  }
}

/**
 * Helper function to validate SKU and transform it to a product id.
 *
 * This is just form magic and not necessary to understand for the order example
 * @param $element
 *   The form element to validate (and update)
 * @param $sku
 *   The sku (or list of skus) provided by the user
 * @param $form_state
 *   The form state
 */
function order_example_validate_sku($element, $sku, &$form_state) {
    // Translate SKUs into product IDs. Use only the first.
    $typed_skus = drupal_explode_tags($sku);
    $typed_sku = reset($typed_skus); // We want only the first.

    // Convert the SKU to a product id.
    if ($product = commerce_product_load_by_sku(trim($typed_sku))) {
      $product_id = $product->product_id;
      form_set_value($element, $product_id, $form_state);
    }
    else {
      form_error($element, t('A valid product is required'));
    }
}
/**
 * Submit handler for order creation.
 */
function order_example_order_creation_submit($form, &$form_state) {
  $product_id = $form_state['values']['product_to_add'];
  $order_id = order_example_create_order_with_product($product_id, $form_state['values']['account_owning_order'], $form_state['values']['use_cart']);

  // Provide links to the admin order page and the checkout process.
  drupal_set_message(t('Order !order created or updated. !checkout', array('!order' => l($order_id, 'admin/commerce/orders/' . $order_id), '!checkout' => l(t('Checkout with this order'), 'checkout/' . $order_id))));
}

/**
 * Validation handler for the simple add-to-cart submit.
 *
 * This just transforms the sku provided into a product id.
 */
function order_example_add_cart_validate($form, &$form_state) {
  $value = array();
  // If a value was entered into the autocomplete...
  if (!empty($form_state['values']['addcart_product'])) {
    order_example_validate_sku($form['simple_add_to_cart']['addcart_product'], $form_state['values']['addcart_product'], $form_state);
  }
}

/**
 * Creates an order (or adds to an existing cart) and line item with the
 * provided with the product id and UID
 *
 * @see http://www.commerceguys.com/node/245
 *
 * @param $product_id
 *   The product ID to be added.
 * @param $uid
 *   The user owning the order.
 * @param $use_cart
 *   If true this will add the product to the user's existing cart, if possible.
 */
function order_example_create_order_with_product($product_id, $uid, $use_cart = TRUE) {
  // First, see if there is already a cart for this user.
  // Here we will not assume that commerce_cart is enabled.
  if (module_exists('commerce_cart') && $use_cart) {
    $order = commerce_cart_order_load($uid);
  }

  if (empty($order)) {
    // Create the new order in checkout status.
    $order = commerce_order_new($uid, 'checkout_checkout');

    // Instead of using the default order type, we could also create an order of
    // a custom order type defined by this module below.
    // $order = commerce_order_new($uid, 'commerce_checkout', 'order_example_order_type');

    // Save the order so its ID is assigned.
    commerce_order_save($order);
  }

  // Load whatever product represents the item the customer will be
  // paying for and create a line item for it.
  $product = commerce_product_load($product_id);

  // Create a line item with quantity 1 and this product.
  $line_item = commerce_product_line_item_new($product, 1, $order->order_id);

  // Save the line item to get its ID.
  commerce_line_item_save($line_item);

  // Add the line item to the order using the wrapper.
  $order_wrapper = entity_metadata_wrapper('commerce_order', $order);
  $order_wrapper->commerce_line_items[] = $line_item;

  // Save the order again to update its line item reference field.
  commerce_order_save($order);

  return $order->order_id;
}

/**
 * Submit handler for the simple add to cart.
 *
 * This uses the default values of commerce_cart_product_add_by_id(), but that
 * function also accepts $quantity, $combine, and $uid arguments.
 *
 * Note that commerce_cart_product_add_by_id() simply wraps up the creation
 * of a line item and the adding of the line item to the product. The code
 * inside is not very hard either.
 */
function order_example_add_cart_submit($form, &$form_state) {
  commerce_cart_product_add_by_id($form_state['values']['addcart_product']);
}

/**
 * Implements hook_modules_enabled().
 *
 * We need to respond when modules are enabled that might implement customer
 * profile types.
 *
 * @param $modules
 */
function order_example_modules_enabled($modules) {
  commerce_order_configure_order_fields($modules, 'order_example_order_type');
}

/**
 * This is a copy of commerce_order_configure_order_fields(). It's necessary
 * here because the order type in that function is hard-wired.
 *
 * Here we respond when modules providing customer profile fields are enabled,
 * adding them to the order.
 *
 * @param $modules
 *   The list of modules which should be checked.
 * @param $type
 *   The order type.
 */
function order_example_configure_order_fields($modules = NULL, $type) {
  // If no modules array is passed, recheck the customer profile reference
  // fields to all customer profile types defined by enabled modules.
  if (empty($modules)) {
    $modules = module_implements('commerce_customer_profile_type_info');
  }

  // Loop through all the enabled modules.
  foreach ($modules as $module) {
    // If the module implements hook_commerce_customer_profile_type_info()...
    if (module_hook($module, 'commerce_customer_profile_type_info')) {
      $profile_types = module_invoke($module, 'commerce_customer_profile_type_info');

      // Loop through and configure its customer profile types.
      foreach ($profile_types as $profile_type) {
        commerce_order_configure_customer_profile_type($profile_type['type'], $profile_type['name'], $type);
      }
    }
  }
}

/**
 * Implements hook_commerce_order_state_info().
 *
 * We add a new "under_construction" state.
 */
function order_example_commerce_order_state_info() {
  $order_states['under_construction'] = array(
    'name' => 'under_construction',
    'title' => t('Under Construction'),
    'description' => t('Orders in this state have been sent to the manufacturer to be constructed.'),
    'weight' => 20,
    'default_status' => 'scheduled',

    // If 'cart' is TRUE then various capabilities of the commerce_cart module
    // are enabled. This includes price recalculation on page reload. Since
    // 'under_construction' is well past the stage that orders should be
    // recalculated, we'll use cart == FALSE here.
    'cart' => FALSE,

    // A status may be disabled (unavailable for use). The default is TRUE,
    // making it available.
    'status' => TRUE,
  );
  return $order_states;
}

/**
 * Implements hook_commerce_order_state_info_alter().
 *
 * Here we want to make sure that our 'under_construction' order state comes
 * right before 'completed', so adjust the weight of each.
 *
 * @param $order_states
 */
function order_example_commerce_order_state_info_alter(&$order_states) {
  if (!empty($order_states['completed']) && $order_states['completed']['weight'] < $order_states['under_construction']['weight']) {
    $order_states['completed']['weight'] += 10;
    $order_states['under_construction']['weight'] = $order_states['completed']['weight'] - 1;
  }
}

/**
 * Implements hook_commerce_order_status_info().
 *
 * Here we add two statuses to the 'under_construction' order state.
 */
function order_example_commerce_order_status_info() {
  $order_statuses['scheduled'] = array(
    'name' => 'scheduled',
    'title' => t('Scheduled'),
    'state' => 'under_construction',
  );
  $order_statuses['shipped_from_vendor'] = array(
    'name' => 'shipped_from_vendor',
    'title' => t('Shipped from vendor'),
    'state' => 'under_construction',
  );

  return $order_statuses;
}