View source
<?php
namespace Drupal\commerce_product_bundle\Plugin\Field\FieldFormatter;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Field\FieldDefinitionInterface;
use Drupal\Core\Field\FieldItemListInterface;
use Drupal\Core\Field\FormatterBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
class BundleItemSelectionDefaultFormatter extends FormatterBase implements ContainerFactoryPluginInterface {
protected $productVariationStorage;
protected $bundleItemStorage;
public function __construct($plugin_id, $plugin_definition, FieldDefinitionInterface $field_definition, array $settings, $label, $view_mode, array $third_party_settings, EntityTypeManagerInterface $entity_type_manager) {
parent::__construct($plugin_id, $plugin_definition, $field_definition, $settings, $label, $view_mode, $third_party_settings);
$this->productVariationStorage = $entity_type_manager
->getStorage('commerce_product_variation');
$this->bundleItemStorage = $entity_type_manager
->getStorage('commerce_product_bundle_i');
}
public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
return new static($plugin_id, $plugin_definition, $configuration['field_definition'], $configuration['settings'], $configuration['label'], $configuration['view_mode'], $configuration['third_party_settings'], $container
->get('entity_type.manager'));
}
public static function defaultSettings() {
return [] + parent::defaultSettings();
}
public function settingsForm(array $form, FormStateInterface $form_state) {
$elements = [];
return $elements;
}
public function viewElements(FieldItemListInterface $items, $langcode) {
$elements = [];
foreach ($items as $delta => $item) {
$qty = $item->qty;
$bundle_item = $this->bundleItemStorage
->load($item->bundle_item)
->label();
$variation = $this->productVariationStorage
->load($item->purchasable_entity)
->label();
$elements[$delta] = [
'#markup' => "{$bundle_item}: ({$qty}) {$variation}",
'#cache' => [
'contexts' => [],
],
];
}
return $elements;
}
}