You are here

public function ShippingRateWidget::extractFormValues in Commerce Shipping 8.2

Extracts field values from submitted form values.

Parameters

\Drupal\Core\Field\FieldItemListInterface $items: The field values. This parameter is altered by reference to receive the incoming form values.

array $form: The form structure where field elements are attached to. This might be a full form structure, or a sub-element of a larger form.

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

Overrides WidgetBase::extractFormValues

File

src/Plugin/Field/FieldWidget/ShippingRateWidget.php, line 159

Class

ShippingRateWidget
Plugin implementation of 'commerce_shipping_rate'.

Namespace

Drupal\commerce_shipping\Plugin\Field\FieldWidget

Code

public function extractFormValues(FieldItemListInterface $items, array $form, FormStateInterface $form_state) {
  $field_name = $this->fieldDefinition
    ->getName();
  $parents = array_merge($form['#parents'], [
    $field_name,
    0,
  ]);
  $element = NestedArray::getValue($form, [
    $field_name,
    'widget',
    0,
  ]);
  $selected_value = NestedArray::getValue($form_state
    ->getValues(), $parents, $key_exists);

  // Fallback to the default rate if the selected rate is no longer valid.
  if (!isset($element[$selected_value]) && isset($element[$element['#default_value']])) {
    $selected_value = $element['#default_value'];
  }
  if ($selected_value && isset($element[$selected_value])) {

    /** @var \Drupal\commerce_shipping\ShippingRate $rate */
    $rate = $element[$selected_value]['#rate'];

    /** @var \Drupal\commerce_shipping\Entity\ShipmentInterface $shipment */
    $shipment = $items
      ->getEntity();
    if ($rate) {
      $this->shipmentManager
        ->applyRate($shipment, $rate);
    }

    // Put delta mapping in $form_state, so that flagErrors() can use it.
    $field_state = static::getWidgetState($form['#parents'], $field_name, $form_state);
    foreach ($items as $delta => $item) {
      $field_state['original_deltas'][$delta] = $delta;
    }
    static::setWidgetState($form['#parents'], $field_name, $form_state, $field_state);
  }
}