I modified a module Commerce Product Comparison by adding hook_form_alter(), so I am adding a new button before and actual "Add to cart" button. Everything works nicely except only when product is on stock. When product is not, Add to cart button is greyed out and also my newly added button does not work. I strongly feel this is something to do with my code for adding a new button. This is the code:
function commerce_product_comparison_form_alter(&$form, &$form_state, $form_id) {
// checking if add_to_cart form is present, also we do not want a button displayed in product page, but only in views
if (strstr($form_id, 'commerce_cart_add_to_cart_form') && !isset($form_state['context']['view_mode'])) {
$entity = (object)$form_state["default_product"];
$product_id = $form_state['default_product']->product_id;
$nid = "";
// query for getting NID of product so it can be passed after
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_id, '=')
->range(0, 1);
if ($result = $query->execute()) {
// Return node id.
$nid = reset($result['node'])->nid;
}
}
// those values works properly even when product is not on stock, I tested it
$form['entity_type'] = array(
'#type' => 'value',
'#value' => 'commerce_product',
);
$form['entity'] = array(
'#type' => 'value',
'#value' => $entity,
);
$form['nid'] = array(
'#type' => 'value',
'#value' => $nid,
);
// Check if the current product already exists in compare list.
$exists = commerce_product_comparison_list_exists('commerce_product', (object)$form_state["default_product"]);
// Check if the compare list isn't already full (4 products max).
$full = commerce_product_comparison_list_is_full();
// I strongly feel there is something wrong with this piece of code, adding the button itself, maybe callback?
$form['add_to_compare_list_form'] = array(
'#type' => 'submit',
'#disabled' => $exists || $full,
'#value' => $exists ? t('In comparison') : ($full ? t('Comparison list full') : t('Add to compare list')),
'#submit' => array('commerce_product_comparison_add_form_submit'),
'#ajax' => array(
'callback' => 'commerce_product_comparison_refresh_comparison_form',
'wrapper' => 'cpc-wrapper' . $form_state['default_product']->product_id,
),
'#prefix' => '<div id="cpc-wrapper' . $form_state['default_product']->product_id . '">',
'#suffix' => '</div>',
);
}
}
'#disabled' => $exists || $full
- what value do$exists
and$full
have in both contexts? Have you checked that they are what you expect?