How to disable Quantity and Remove line item fields for product type with Drupal 7 Commerce

The Commerce Shopping Cart is produced with Views. This makes it easy to modify, but difficult to conditionally manipulate the line items with Rules.

That's where hook_form_alter() comes to the rescue with the help of entity_metadata_wrapper(). Looping through the line items makes it possible to disable the Quantity and Remove fields for line items of a particular product type. Accomplishing this however is not immediately obvious as it requires comparing the shopping cart line item ID with the form line item ID attribute.

With that in mind, the following code illustrates how to disable the Quantity and Remove fields for line items of a particular product type.

<?php
/**
 * Implements hook_form_alter().
 */
function custom_form_alter(&$form, $form_state, $form_id) {
  if (
$form_id == 'views_form_commerce_cart_form_default') {
    global
$user;
   
$product_types = array('pickup', 'delivery');
   
$cart = commerce_cart_order_load($user->uid);
    foreach (
entity_metadata_wrapper('commerce_order', $cart)->commerce_line_items as $delta => $line_item_wrapper) {
     
// Check current line item product type against list of types to be disabled.
     
if (in_array($line_item_wrapper->commerce_product->value()->type, $product_types)) {
        foreach (
$form['edit_quantity'] as $index => $line_item) {
          if (
is_numeric($index)) {
           
// Compare the current shopping cart line item ID to the form line item ID.
           
if ($line_item_wrapper->raw() == $form["edit_quantity"][$index]['#line_item_id']) {
             
$form['edit_quantity'][$index]['#attributes']['readonly'] = 'readonly';
             
$form['edit_quantity'][$index]['#attributes']['disabled'] = TRUE;
             
$form['edit_quantity'][$index]['#attributes']['title'] = t('This quantity cannot be changed.');
              unset(
$form['edit_delete'][$index]);
            }
          }
        }
      }
    }
  }
}
?>

Add new comment

Plain text

  • No HTML tags allowed.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Lines and paragraphs break automatically.