You are here

public static function ProductBundleWidgetBase::ajaxRefresh in Commerce Product Bundle 8

#ajax callback: Replaces the rendered fields on variation change.

Assumes the existence of a 'selected_variation' in $form_state.

@todo We will need to support the existence of MULTIPLE selected variations.

File

src/Plugin/Field/FieldWidget/ProductBundleWidgetBase.php, line 137

Class

ProductBundleWidgetBase
Provides the base structure for product bundle widgets.

Namespace

Drupal\commerce_product_bundle\Plugin\Field\FieldWidget

Code

public static function ajaxRefresh(array $form, FormStateInterface $form_state) {

  /** @var \Drupal\Core\Render\MainContent\MainContentRendererInterface $ajax_renderer */
  $ajax_renderer = \Drupal::service('main_content_renderer.ajax');
  $request = \Drupal::request();
  $route_match = \Drupal::service('current_route_match');

  /** @var \Drupal\Core\Ajax\AjaxResponse $response */
  $variation_parents = array_slice($form_state
    ->getTriggeringElement()['#array_parents'], 0, 5);
  $variation_form = NestedArray::getValue($form, $variation_parents);
  $response = $ajax_renderer
    ->renderResponse($variation_form, $request, $route_match);
  $selected_variation_key = implode('][', array_merge($variation_parents, [
    'selected_variation',
  ]));
  $selected_variation_id = $form_state
    ->get($selected_variation_key);
  $variation = ProductVariation::load($selected_variation_id);

  /** @var \Drupal\commerce_product\ProductVariationFieldRendererInterface $variation_field_renderer */
  $variation_field_renderer = \Drupal::service('commerce_product.variation_field_renderer');
  $view_mode = $form_state
    ->get('form_display')
    ->getMode();
  $variation_field_renderer
    ->replaceRenderedFields($response, $variation, $view_mode);

  // Allow modules to add arbitrary ajax commands to the response.
  $event = new ProductVariationAjaxChangeEvent($variation, $response, $view_mode);
  $event_dispatcher = \Drupal::service('event_dispatcher');
  $event_dispatcher
    ->dispatch(ProductEvents::PRODUCT_VARIATION_AJAX_CHANGE, $event);
  return $response;
}