0

I need to allow the costumers to choose specific quantities for specific type of products but I would like to avoid adding 2 extra modules to my website ( Commerce Extended Quantity & Extended Number Field). So I used a form alter function like here Set default "Quantity" dropdown select in product. Commerce Kickstart.

The issue is that the input is transformed to a dropdown but when the form is submitted, a blank page appears with the message "The website encountered an unexpected error" and the error in admin/reports/dblog is Cannot unset string offsets in Drupal\Core\Field\WidgetBase->extractFormValues()... Here is the code I use:

function mymodule_form_alter(&$form, $form_state, $form_id) {

  if (strpos($form_id, "commerce_order_item_add_to_cart_form") !== false) {

  // Change widget type of quantity to select list
 $form['quantity'] = array(
'#title' => t('Quantity'),
'#type' => 'select',
'#datatype' => 'integer', // <-- I added this one to fix Notice: Undefined index: #datatype in commerce_cart_add_to_cart_form_validate() when you click add to cart button
'#options' => array(
  1 => '1',
  2 => '2',
  3 => '3'
)
);   


 }}

Does anybody know if there is a way to fix this error? Thanks!

1 Answer 1

0

I found the solution to my issue:

 function mymodule_form_alter(&$form, $form_state, $form_id) {

 if (strpos($form_id, "commerce_order_item_add_to_cart_form") !== false) {
$form['quantity']['widget'][0]['value']['#default_value'] = 1;
 $form['quantity']['widget'][0]['value']['#step'] = 0.5;
   $form['quantity']['widget'][0]['value']['#min'] = 1;
    $form['quantity']['widget'][0]['value']['#max'] = 3;
    $form['quantity']['widget'][0]['value']['#type'] = 'select';       
 $form['quantity']['widget'][0]['value']['#options'] = array(
 '1' => t('1 hour'),
'1.5' => t('1,5 hour'),   
  '2' => t('2 hours'),
   '2.5' => t('2,5 hours'),
   '3' => t('3 hours') );
    }}
1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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