Commerce Stock warnings on Shopping cart page

If you happen to have Commerce Stock module enabled, while at the same time you have removed Commerce Line Item: Delete button field from your Shopping cart form view, you most probably faced (or are still facing) some nasty PHP warning and notices when using any of the shopping cart buttons.

If you happen to have Commerce Stock module enabled, while at the same time you have removed Commerce Line Item: Delete button field from your Shopping cart form view, you most probably faced (or are still facing) the following PHP warning and notices when using any of the shopping cart buttons:

  • Notice: Undefined index: line_items in commerce_stock_form_commerce_cart_validate() (line 198 of /modules/contrib/commerce_stock/commerce_stock.module).
  • Warning: array_keys() expects parameter 1 to be array, null given in commerce_stock_form_commerce_cart_validate() (line 198 of /modules/contrib/commerce_stock/commerce_stock.module).
  • Notice: Undefined index: line_items in commerce_stock_form_commerce_cart_validate() (line 201 of /modules/contrib/commerce_stock/commerce_stock.module).

They are caused by Commerce Stock module assuming the existence of line_items array in the $form_state - which is added only if Commerce Line Item: Delete button field was not removed from the Shopping cart form view (see commerce_cart_form_alter()). There are two possible solutions to fix this issue:

1) Hide instead of deleting

Do not remove the Commerce Line Item: Delete button field from the view, just hide it instead (tick Exclude from display in field configuration) - this way the $form_state['line_items'] will be still populated, even if the delete buttons are no longer visible on the shopping cart page.

2) Add missing line_items yourself

If you still prefer to remove the Commerce Line Item: Delete button field from the view, it will be enough to add a simple hook_form_alter() implementation to have $form_state['line_items'] populated. Something like:

/**
 * Implements hook_form_alter().
 *
 * When the 'Commerce Line Item: Delete button' field is removed from the
 * 'Shopping cart form' view, line items are no longer added to the $form_state.
 * There are modules though that assume their existence there (commerce_stock
 * for example), therefore we need to add them anyway to avoid PHP warnings.
 *
 * @see commerce_cart_form_alter()
 * @see commerce_line_item_handler_field_edit_delete::views_form()
 */
function mymodule_form_alter(&$form, &$form_state, $form_id) {
  if (
    strpos($form_id, 'views_form_commerce_cart_form_') === 1
    && empty($form['edit_delete'])
  ) {
    $form_state['line_items'] = array();
    $order_wrapper = entity_metadata_wrapper('commerce_order', $form_state['order']);
    foreach ($order_wrapper->commerce_line_items as $line_item_wrapper) {
      $line_item = $line_item_wrapper->value();
      $form_state['line_items'][$line_item->line_item_id] = $line_item;
    }
  }
}