ProductVariationFieldRenderer.php in Commerce Core 8.2
File
modules/product/src/ProductVariationFieldRenderer.php
View source
<?php
namespace Drupal\commerce_product;
use Drupal\commerce_product\Entity\ProductVariationInterface;
use Drupal\Core\Ajax\AjaxResponse;
use Drupal\Core\Ajax\ReplaceCommand;
use Drupal\Core\Render\Element;
use Drupal\Core\Entity\EntityTypeManagerInterface;
class ProductVariationFieldRenderer implements ProductVariationFieldRendererInterface {
protected $variationViewBuilder;
public function __construct(EntityTypeManagerInterface $entity_type_manager) {
$this->variationViewBuilder = $entity_type_manager
->getViewBuilder('commerce_product_variation');
}
public function renderFields(ProductVariationInterface $variation, $view_mode = 'default') {
$build = $this->variationViewBuilder
->view($variation, $view_mode);
foreach ($build['#pre_render'] as $callable) {
$build = call_user_func($callable, $build);
}
unset($build['#pre_render']);
unset($build['product_id']);
foreach (array_keys($build) as $key) {
if (Element::property($key)) {
unset($build[$key]);
}
}
foreach ($build as $field_name => $rendered_field) {
$build[$field_name] = $this
->prepareForAjax($rendered_field, $field_name, $variation);
}
return $build;
}
public function renderField($field_name, ProductVariationInterface $variation, $display_options = []) {
$rendered_field = $this->variationViewBuilder
->viewField($variation
->get($field_name), $display_options);
if (!empty($rendered_field)) {
$rendered_field = $this
->prepareForAjax($rendered_field, $field_name, $variation);
}
return $rendered_field;
}
public function replaceRenderedFields(AjaxResponse $response, ProductVariationInterface $variation, $view_mode = 'default') {
$rendered_fields = $this
->renderFields($variation, $view_mode);
foreach ($rendered_fields as $field_name => $rendered_field) {
$response
->addCommand(new ReplaceCommand('.' . $rendered_field['#ajax_replace_class'], $rendered_field));
}
}
protected function prepareForAjax(array $rendered_field, $field_name, ProductVariationInterface $variation) {
$ajax_class = $this
->buildAjaxReplacementClass($field_name, $variation);
$rendered_field['#attributes']['class'][] = $ajax_class;
$rendered_field['#ajax_replace_class'] = $ajax_class;
if (!Element::children($rendered_field)) {
$rendered_field['#type'] = 'container';
}
return $rendered_field;
}
protected function buildAjaxReplacementClass($field_name, ProductVariationInterface $variation) {
return 'product--variation-field--variation_' . $field_name . '__' . $variation
->getProductId();
}
}