0

I'm having a tough time setting a default value on an Address field during Commerce checkout.

The Address (profile) is set to use the Address First & Last name fields and I'm trying to set their default values (since the user already entered their name on the registration page prior).

I've tried _form_alter, _preprocess_input, and _field_widget_form_alter - but I am not able to get any of these to work - I suspect because the address widget is displayed on a Commerce checkout screen may be making this more difficult.

Any advise on how to set these default values?

Drupal 10 / Commerce

1 Answer 1

0
function MODULE_form_commerce_checkout_flow_multistep_default_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {

  if ($form['#step_id'] == 'order_information') {

    // Set first & last name from user account
    $form['payment_information']['add_payment_method']['billing_information']['address']['widget'][0]['address']['#pre_render'][] =  [MyPreRenders::class, 'recurringCodePrerender'];
}

MODULE/src/MyPreRenders

namespace Drupal\MODULE;

use Drupal\Core\Security\TrustedCallbackInterface;
use Drupal\Core\Security\Attribute\TrustedCallback;

class MyPreRenders {
  #[TrustedCallback]
  public static function recurringCodePrerender($form) {

    $user = \Drupal\user\Entity\User::load(\Drupal::currentUser()->id());

    $form['given_name']['#value'] = $user->get('field_first_name')->value;
    $form['family_name']['#value'] = $user->get('field_last_name')->value;

    return $form;
  }
}

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.