0

I have tried to add default value to an existing field using hook_form_alter() but it does not work.

Below is the html of the fields

<fieldset class="js-form-item js-form-type-textfield form-type-textfield js-form-item-order-fieldscheckout-field-my-fieldname-0-value form-item-order-fieldscheckout-field-my-fieldname-0-value form-group" style="display: block;">
  <label for="edit-order-fieldscheckout-field-my-fieldname-0-value">field Label</label>
  <input class="js-text-full text-full form-control" data-drupal-selector="edit-order-fieldscheckout-field-my-fieldname-0-value" type="text" id="edit-order-fieldscheckout-field-my-fieldname-0-value" name="order_fields:checkout[field_my_fieldname][0][value]" value="" size="60" maxlength="9" placeholder="">
</fieldset> 

Below is the code that I tried to set default value in the field

function module_name_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
  if ($form_id == 'commerce_checkout_flow_multistep_default') {
    $form['field_my_fieldname'][LANGUAGE_NONE][0]['value']['#type'] = 'hidden';
    $form['field_my_fieldname']['widget'][0]['value']['#value'] = 1;
    // Tried to add class attribute but not working
    $form['field_my_fieldname']['#attributes']['class'][] = '123456789';
  }
}
1

I could make your code work like this:

function module_name_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
  if ($form_id == 'commerce_checkout_flow_multistep_default') {
    $form['field_my_fieldname']['widget'][0]['value']['#type'] = 'hidden';
    $form['field_my_fieldname']['widget'][0]['value']['#value'] = 1;
    $form['field_my_fieldname']['widget'][0]['value']['#attributes']['class'][] = '123456789';
  }
}

Note that LANGUAGE_NONE is Drupal 7 specific and won't work in Drupal 8 and newer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy