2

A common question I hear is "How can I prevent a product from being added to the cart?" There are several reasons why you'd want to do this, most end up being related to some logic being required to determine if a product is eligible without actually deactivating the Add to Cart button.

5

While you probably ought to actually disable the Add to Cart button, you'd actually put logic for determining whether or not a product should be added to the cart in a validate handler.

The first step us to add a form_alter hook that adds a validation handler to the add to cart forms.

/**
 * Implements hook_form_FORM_ID_alter().
 */
function MYMODULE_form_commerce_cart_add_to_cart_form_alter(&$form, &$form_state) {
  // Add a validate hook so that the order can be checked to ensure that the
  // our constraints are met.
  array_unshift($form['#validate'], 'MYMODULE_validate_some_stuff');
}

Note: this works because of commerce_cart_forms() which adds the generic form callback instead of requiring us to look for the string in the $form_id.

Now, you just need to implement your logic:

/*
 * Check the product/order against my constraints.
 */
function MYMODULE_validate_some_stuff(&$form, &$form_state) {
  $order = commerce_cart_order_load($form_state['values']['uid']);
  $line_item = $form_state['line_item'];

  if (/* your logic here */) {
    form_set_error('product_id', t('Sorry, you can\'t do that!'));
  }
}

You'll notice that the commerce_order is loaded by the user's UID and you've got access to the commerce_line_item that you can then use to grab the product (use $line_item->commerce_product). Also, there is no need to return TRUE or FALSE. Just set an error.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.