Drupal Commerce - "Select a product" element: How to change the select list to radio buttons
User login
Wednesday, July 18, 2012 - 13:57
Here is the code that changes the default select list of "Select a product" element of Drupal Commerce to radio buttons, for a standalone product list.
The following goes in a custom module (tested in Drupal 7).
<?php
function MYMODULE_form_alter(&$form, $form_state, $form_id) {
if (strpos($form_id, 'commerce_cart_add_to_cart_form_') === 0 && isset($form['product_id'])) {
$form['product_id']['#type'] = "radios";
}
}
?>
Check this for code for the product select list shown in conjunction with product attributes.
-- UPDATED!! --
Further to Ryan's comment below, here is the updated code where options are sanitized.
( Sanitize = convert to plain text -> remove html / js. Without this, html / js included in product titles will render in product options, posing a security threat.)
<?php
function MYMODULE_form_alter(&$form, $form_state, $form_id) {
if (strpos($form_id, 'commerce_cart_add_to_cart_form_') === 0 && isset($form['product_id'])) {
// Sanitization of select options will occur in a check_plain() in
// the function form_select_options(). We change this element to
// another #type, 'radios', and hence we are also responsible for looping
// over its #options array and sanitizing the values.
foreach ($form['product_id']['#options'] as $key => $value) {
$form['product_id']['#options'][$key] = check_plain($value);
}
// Change element to #type radios.
$form['product_id']['#type'] = "radios";
}
}
?>
Further discussion takes place here.
Tags:
Drupal Commerce, Drupal Quick Tips