You are here

public static function ProductVariationWidgetBase::ajaxRefresh in Commerce Core 8.2

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

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

File

modules/product/src/Plugin/Field/FieldWidget/ProductVariationWidgetBase.php, line 110

Class

ProductVariationWidgetBase
Provides the base structure for product variation widgets.

Namespace

Drupal\commerce_product\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 */
  $response = $ajax_renderer
    ->renderResponse($form, $request, $route_match);
  $variation = ProductVariation::load($form_state
    ->get('selected_variation'));

  /** @var \Drupal\commerce_product\Entity\ProductInterface $product */
  $product = $form_state
    ->get('product');
  if ($variation
    ->hasTranslation($product
    ->language()
    ->getId())) {
    $variation = $variation
      ->getTranslation($product
      ->language()
      ->getId());
  }

  /** @var \Drupal\commerce_product\ProductVariationFieldRendererInterface $variation_field_renderer */
  $variation_field_renderer = \Drupal::service('commerce_product.variation_field_renderer');
  $view_mode = $form_state
    ->get('view_mode');
  $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;
}