You are here

public function CustomerProfileAlter::alter in Drupal Commerce Connector for AvaTax 8

Alters the inline form to add address validation logic.

Parameters

array $inline_form: The inline form.

\Drupal\Core\Form\FormStateInterface $form_state: The current state of the form.

Overrides CustomerProfileAlterInterface::alter

File

src/CustomerProfileAlter.php, line 79

Class

CustomerProfileAlter
The customer profile alter for address validation.

Namespace

Drupal\commerce_avatax

Code

public function alter(array &$inline_form, FormStateInterface $form_state) {
  assert($inline_form['#inline_form'] instanceof CustomerProfile);
  $inline_form['#attached']['library'][] = 'commerce_avatax/address';
  $inline_form['#attributes']['class'][] = 'avatax-form';

  // Determine if we have existing profile or we adding new / editing
  // existing one.
  $rendered = isset($inline_form['rendered']);

  // Used to hold the proposed address suggestion.
  $inline_form['address_suggestion'] = [
    '#type' => 'hidden',
  ];
  $endpoint = Url::fromRoute('commerce_avatax.address_validator', [], [
    'query' => [
      'token' => $this->csrf
        ->get('commerce-avatax/address-validator'),
    ],
  ])
    ->setAbsolute();

  // Set ID for JS more precise targeting.
  $js_data = [
    'inline_id' => $inline_form['#id'],
    'countries' => $this->config
      ->get('address_validation.countries'),
    'rendered' => $rendered,
    'endpoint' => $endpoint
      ->toString(),
  ];
  $profile = $inline_form['#inline_form']
    ->getEntity();
  if ($profile !== NULL) {
    $address = $profile
      ->get('address')
      ->first();
    assert($address instanceof AddressItem);
    $js_data['address'] = $address
      ->toArray();
    $js_data['country'] = $address
      ->getCountryCode() ?? $inline_form['address']['widget'][0]['address']['#default_value']['country_code'];
    $js_data['fields'] = [
      'address_line1',
      'address_line2',
      'locality',
      'administrative_area',
      'country_code',
      'postal_code',
    ];
  }
  $inline_form['#attached']['drupalSettings']['commerceAvatax'] = $js_data;

  // Add ours validation and submit handlers.
  $inline_form['#element_validate'][] = [
    $this,
    'submitForm',
  ];
}