Drupal Commerce - "Select a product" element: How to change the select list to radio buttons

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.

Recent Comments

Forward by Dries Buytaert, Founder and Project Lead, Drupal; CTO Acquia.

Order now from:

Managing Expectations Podcast with DrupalEasy

Author Interview http://tinyurl.com/8a8nxno

We provide the most Shiny Drupal Bits & Pixels

Since Drupal 4.x

© 2014 Konordo Limited
Drupal Services provider.
All rights reserved.

Reg Nr. 12301661F
VAT Nr. CY10301661D

M. Director: Konstantin Ordoulidis

 

Get in touch

  • Omirou 10, 3095, Limassol, Cyprus
  • +4917698807355
  • info [at] konordo [dot] com

Submit