public function commerce_add_to_cart_extras_handler_field_quantity::views_form_submit in Commerce Add to Cart Extras 7
File
- ./
commerce_add_to_cart_extras_handler_field_quantity.inc, line 147 - Views field handler. Adds the quantity field to the view. Implements the Views Form API.
Class
- commerce_add_to_cart_extras_handler_field_quantity
- Views field handler.
Code
public function views_form_submit($form, &$form_state) {
global $user;
$field_name = $this->options['id'];
$product_quantities = array();
foreach (element_children($form[$field_name]) as $row_id) {
// Don't add products that have quantity 0.
$quantity = $form_state['values'][$field_name][$row_id];
if ($quantity > 0) {
$product_id = $form[$field_name][$row_id]['#product_id'];
$product_quantities[$product_id] = $quantity;
}
}
$products = commerce_product_load_multiple(array_keys($product_quantities));
foreach ($products as $product_id => $product) {
$quantity = $product_quantities[$product_id];
$line_item = commerce_product_line_item_new($product, $quantity);
$line_item->data['context']['product_ids'] = array(
$product_id,
);
$line_item->data['context']['add_to_cart_combine'] = $this->options['combine'];
// Add the display path to the line item's context data array if
// specified.
if ($this->options['display_path']) {
if (empty($this->options['display_path_option']) || $this->options['display_path_option'] == 'page') {
$path = current_path();
}
elseif ($this->options['display_path_option'] == 'referencing_product') {
// Via: http://www.drupalcommerce.org/node/3176
// Iterate thhrough fields which refer to products.
foreach (commerce_info_fields('commerce_product_reference') as $field) {
// Build query.
$query = new EntityFieldQuery();
$query
->entityCondition('entity_type', 'node', '=')
->fieldCondition($field['field_name'], 'product_id', $product->product_id, '=')
->range(0, 1);
if ($result = $query
->execute()) {
$array_keys = array_keys($result['node']);
$path = 'node/' . reset($array_keys);
}
}
// Generally, people would expect a path to be provided, so if it
// doesn't work, set to the current page.
if (empty($path)) {
$path = current_path();
}
}
elseif ($this->options['display_path_option'] == 'custom') {
$path = !empty($this->options['display_path_other']) ? $this->options['display_path_other'] : '';
}
// Set the path on the line item.
$line_item->data['context']['display_path'] = $path;
}
// Store the View data in the context data array as well.
$line_item->data['context']['view'] = array(
'view_name' => $this->view->name,
'display_name' => $this->view->current_display,
'human_name' => $this->view->human_name,
'page' => $this->view->current_page,
);
commerce_cart_product_add($user->uid, $line_item, $this->options['combine']);
}
if (count($product_quantities)) {
drupal_set_message(t('The selected products have been added to <a href="!cart-url">your cart</a>.', array(
'!cart-url' => url('cart'),
)));
}
}