You are here

class ProductBundleItemsWidget in Commerce Product Bundle 8

Plugin implementation of the 'commerce_product_bundle_items' widget.

Plugin annotation


@FieldWidget(
  id = "commerce_product_bundle_items",
  label = @Translation("Product bundle items"),
  field_types = {
    "entity_reference"
  }
)

Hierarchy

Expanded class hierarchy of ProductBundleItemsWidget

File

src/Plugin/Field/FieldWidget/ProductBundleItemsWidget.php, line 28

Namespace

Drupal\commerce_product_bundle\Plugin\Field\FieldWidget
View source
class ProductBundleItemsWidget extends ProductBundleWidgetBase {

  /**
   * NOTES:.
   *
   *  1. This is based off of ProductVariationAttributesWidget which handled
   *     product -> (1) VARIATION selection based on available attributes.
   *  2. This widget will need to handle
   *     bundle -> (products) -> (MANY) VARIATIONS selections based on attributes
   *     So it will need to do everything ProductVariationAttributesWidget does
   *     but also handle multiple selections.
   */

  /**
   * The product attribute storage.
   *
   * @var \Drupal\Core\Entity\EntityStorageInterface
   */
  protected $attributeStorage;

  /**
   * The attribute field manager.
   *
   * @var \Drupal\commerce_product\ProductAttributeFieldManagerInterface
   */
  protected $attributeFieldManager;

  /**
   * Constructs a new ProductBundleItemsWidget object.
   *
   * @param string $plugin_id
   *   The plugin_id for the widget.
   * @param mixed $plugin_definition
   *   The plugin implementation definition.
   * @param \Drupal\Core\Field\FieldDefinitionInterface $field_definition
   *   The definition of the field to which the widget is associated.
   * @param array $settings
   *   The widget settings.
   * @param array $third_party_settings
   *   Any third party settings.
   * @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager
   *   The entity type manager.
   * @param \Drupal\commerce_product\ProductAttributeFieldManagerInterface $attribute_field_manager
   *   The attribute field manager.
   */
  public function __construct($plugin_id, $plugin_definition, FieldDefinitionInterface $field_definition, array $settings, array $third_party_settings, EntityTypeManagerInterface $entity_type_manager, ProductAttributeFieldManagerInterface $attribute_field_manager) {
    parent::__construct($plugin_id, $plugin_definition, $field_definition, $settings, $third_party_settings, $entity_type_manager);
    $this->attributeStorage = $entity_type_manager
      ->getStorage('commerce_product_attribute');
    $this->attributeFieldManager = $attribute_field_manager;
  }

  /**
   * {@inheritdoc}
   */
  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['third_party_settings'], $container
      ->get('entity_type.manager'), $container
      ->get('commerce_product.attribute_field_manager'));
  }

  /**
   * {@inheritdoc}
   */
  public function formElement(FieldItemListInterface $items, $delta, array $element, array &$form, FormStateInterface $form_state) {

    /** @var \Drupal\commerce_product_bundle\Entity\BundleInterface $product_bundle */
    $bundle = $form_state
      ->get('product_bundle');
    $element['bundle'] = [
      '#type' => 'value',
      '#value' => $bundle
        ->id(),
    ];
    $element['bundle_items'] = [];

    /** @var \Drupal\commerce_product_bundle\Entity\BundleItemInterface $bundle_item */
    foreach ($bundle
      ->getBundleItems() as $bundle_item) {
      $parents = [
        $items
          ->getName(),
        $delta,
        'bundle_items',
        $bundle_item
          ->id(),
      ];
      $element['bundle_items'][$bundle_item
        ->id()] = $this
        ->getBundleItemForm($bundle_item, $form, $form_state, $parents);
    }
    $form['#entity_builders'][] = [
      $this,
      'addBundleItemSelections',
    ];
    return $element;
  }

  /**
   * Gets the child form element for a given bundle item.
   *
   * @param \Drupal\commerce_product_bundle\Entity\BundleItemInterface $bundle_item
   *   The bundle item.
   * @param array $form
   *   The complete form array.
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   *   The current state of the form.
   * @param array $parents
   *   The parents of the bundle item form element in the form structure.
   *
   * @return array
   *   A renderable form array for the given bundle item.
   */
  private function getBundleItemForm(BundleItemInterface $bundle_item, array &$form, FormStateInterface $form_state, array $parents) {
    $bundle_item_form = [
      'bundle_item' => [
        '#type' => 'value',
        '#value' => $bundle_item,
      ],
    ];

    /** @var \Drupal\commerce_product\Entity\ProductInterface $product */
    $product = $bundle_item
      ->getProduct();

    /** @var \Drupal\commerce_product\Entity\ProductVariationInterface[] $variations */
    $variations = $bundle_item
      ->getVariations();
    $min_qty = $bundle_item
      ->getMinimumQuantity();
    $max_qty = $bundle_item
      ->getMaximumQuantity();
    if ($min_qty === $max_qty) {
      $bundle_item_form['qty'] = [
        '#type' => 'value',
        '#value' => $bundle_item
          ->getQuantity(),
      ];
    }
    else {
      $bundle_item_form['qty'] = [
        '#type' => 'number',
        '#title' => $this
          ->t('Quantity'),
        '#min' => $min_qty,
        '#max' => $max_qty,
        '#default_value' => $min_qty,
        '#step' => 1,
      ];
    }
    if (count($variations) === 0) {

      // Nothing to purchase, tell the parent form to hide itself.
      $form_state
        ->set('hide_form', TRUE);
      $bundle_item_form['variation'] = [
        '#type' => 'value',
        '#value' => 0,
      ];
      return $bundle_item_form;
    }
    elseif (count($variations) === 1) {

      /** @var \Drupal\commerce_product\Entity\ProductVariationInterface $selected_variation */
      $selected_variation = reset($variations);

      // For regular products, from which this logic was adapted, the variation
      // form is only hidden (with simply this value stored) when the variation
      // has no attribute fields (to show the customer which variation they are
      // purchasing). But since the product bundle is expected to indicate the
      // items in the bundle, and to avoid unnecessary UI clutter, we hide all
      // attribute widgets when there is only one variation.
      // Compare this with ProductVariationAttributesWidget::formElement.
      $bundle_item_form['variation'] = [
        '#type' => 'value',
        '#value' => $selected_variation
          ->id(),
      ];
      $bundle_item
        ->setCurrentVariation($selected_variation);
      $bundle_item_form['title'] = [
        '#type' => 'markup',
        '#markup' => $bundle_item
          ->getTitle(),
        '#prefix' => '<p>',
        '#suffix' => '</p>',
      ];
      return $bundle_item_form;
    }

    // Build the bundle item's full attribute form.
    $wrapper_id = Html::getUniqueId('commerce-product-bundle-item-add-to-cart-form');
    $bundle_item_form += [
      '#wrapper_id' => $wrapper_id,
      '#prefix' => '<div id="' . $wrapper_id . '">',
      '#suffix' => '</div>',
    ];
    $user_input = (array) NestedArray::getValue($form_state
      ->getUserInput(), $parents);
    if (!empty($user_input)) {
      $selected_variation = $this
        ->selectVariationFromUserInput($variations, $user_input);
    }
    else {
      $selected_variation = $this->variationStorage
        ->loadFromContext($product);

      // The returned variation must also be enabled.
      if (!in_array($selected_variation, $variations)) {
        $selected_variation = reset($variations);
      }
    }
    $bundle_item_form['variation'] = [
      '#type' => 'value',
      '#value' => $selected_variation
        ->id(),
    ];
    $bundle_item
      ->setCurrentVariation($selected_variation);

    // Set the selected variation in the form state for our AJAX callback.
    $form_state
      ->set('purchased_entity][widget][0][bundle_items][' . $bundle_item
      ->id() . '][selected_variation', $selected_variation
      ->id());
    $bundle_item_form['attributes'] = [
      '#type' => 'container',
      '#attributes' => [
        'class' => [
          'attribute-widgets',
        ],
      ],
    ];
    foreach ($this
      ->getItemAttributeInfo($selected_variation, $variations) as $field_name => $attribute) {
      $bundle_item_form['attributes'][$field_name] = [
        '#type' => $attribute['element_type'],
        '#title' => $attribute['title'],
        '#options' => $attribute['values'],
        '#required' => $attribute['required'],
        '#default_value' => $selected_variation
          ->getAttributeValueId($field_name),
        '#ajax' => [
          'callback' => [
            get_class($this),
            'ajaxRefresh',
          ],
          'wrapper' => $bundle_item_form['#wrapper_id'],
        ],
      ];

      // Convert the _none option into #empty_value.
      if (isset($bundle_item_form['attributes'][$field_name]['#options']['_none'])) {
        if (!$bundle_item_form['attributes'][$field_name]['#required']) {
          $bundle_item_form['attributes'][$field_name]['#empty_value'] = '';
        }
        unset($bundle_item_form['attributes'][$field_name]['#options']['_none']);
      }

      // 1 required value -> Disable the bundle_item_variations to skip unneeded ajax calls.
      if ($attribute['required'] && count($attribute['values']) === 1) {
        $bundle_item_form['attributes'][$field_name]['#disabled'] = TRUE;
      }

      // Optimize the UX of optional attributes:
      // - Hide attributes that have no values.
      // - Require attributes that have a value on each variation.
      if (empty($bundle_item_form['attributes'][$field_name]['#options'])) {
        $bundle_item_form['attributes'][$field_name]['#access'] = FALSE;
      }
      if (!isset($bundle_item_form['attributes'][$field_name]['#empty_value'])) {
        $bundle_item_form['attributes'][$field_name]['#required'] = TRUE;
      }
    }
    return $bundle_item_form;
  }

  /**
   * Selects a product variation from user input.
   *
   * If there's no user input (form viewed for the first time), the default
   * variations are returned.
   *
   * @param \Drupal\commerce_product\Entity\ProductVariationInterface[] $variations
   *   An array of product variations.
   * @param array $user_input
   *   The user input.
   *
   * @return \Drupal\commerce_product\Entity\ProductVariationInterface
   *   The selected variation.
   */
  protected function selectVariationFromUserInput(array $variations, array $user_input) {
    $current_variation = reset($variations);
    if (!empty($user_input)) {
      $attributes = $user_input['attributes'];
      foreach ($variations as $variation) {
        $match = TRUE;
        foreach ($attributes as $field_name => $value) {
          if ($variation
            ->getAttributeValueId($field_name) != $value) {
            $match = FALSE;
          }
        }
        if ($match) {
          $current_variation = $variation;
          break;
        }
      }
    }
    return $current_variation;
  }

  /**
   * Gets the attribute information for the selected product variation.
   *
   * @param \Drupal\commerce_product\Entity\ProductVariationInterface $selected_variation
   *   The selected product variation.
   * @param \Drupal\commerce_product\Entity\ProductVariationInterface[] $variations
   *   The available product variations.
   *
   * @return array[]
   *   The attribute information, keyed by field name.
   */
  protected function getItemAttributeInfo(ProductVariationInterface $selected_variation, array $variations) {
    $attributes = [];
    $field_definitions = $this->attributeFieldManager
      ->getFieldDefinitions($selected_variation
      ->bundle());
    $field_map = $this->attributeFieldManager
      ->getFieldMap($selected_variation
      ->bundle());
    $field_names = array_column($field_map, 'field_name');
    $index = 0;
    foreach ($field_names as $field_name) {

      /** @var \Drupal\commerce_product\Entity\ProductAttributeInterface $attribute_type */
      $attribute_type = $this->attributeStorage
        ->load(substr($field_name, 10));
      $field = $field_definitions[$field_name];
      $attributes[$field_name] = [
        'field_name' => $field_name,
        'title' => $field
          ->getLabel(),
        'required' => $field
          ->isRequired(),
        'element_type' => $attribute_type
          ->getElementType(),
      ];

      // The first attribute gets all values. Every next attribute gets only
      // the values from variations matching the previous attribute value.
      // For 'Color' and 'Size' attributes that means getting the colors of all
      // variations, but only the sizes of variations with the selected color.
      $callback = NULL;
      if ($index > 0) {
        $previous_field_name = $field_names[$index - 1];
        $previous_field_value = $selected_variation
          ->getAttributeValueId($previous_field_name);
        $callback = function ($variation) use ($previous_field_name, $previous_field_value) {

          /** @var \Drupal\commerce_product\Entity\ProductVariationInterface $variation */
          return $variation
            ->getAttributeValueId($previous_field_name) == $previous_field_value;
        };
      }
      $attributes[$field_name]['values'] = $this
        ->getAttributeValues($variations, $field_name, $callback);
      $index++;
    }

    // Filter out attributes with no values.
    $attributes = array_filter($attributes, function ($attribute) {
      return !empty($attribute['values']);
    });
    return $attributes;
  }

  /**
   * Gets the attribute values of a given set of variations.
   *
   * @param \Drupal\commerce_product\Entity\ProductVariationInterface[] $variations
   *   The variations.
   * @param string $field_name
   *   The field name of the attribute.
   * @param callable|null $callback
   *   An optional callback to use for filtering the list.
   *
   * @return array[]
   *   The attribute values, keyed by attribute ID.
   */
  protected function getAttributeValues(array $variations, $field_name, callable $callback = NULL) {
    $values = [];
    foreach ($variations as $variation) {
      if (is_null($callback) || call_user_func($callback, $variation)) {
        $attribute_value = $variation
          ->getAttributeValue($field_name);
        if ($attribute_value) {
          $values[$attribute_value
            ->id()] = $attribute_value
            ->label();
        }
        else {
          $values['_none'] = '';
        }
      }
    }
    return $values;
  }

  /**
   * Entity builder: updates the order item with the bundle item selections.
   *
   * @param string $entity_type
   *   The entity type.
   * @param \Drupal\commerce_order\Entity\OrderItemInterface $order_item
   *   The entity updated with the submitted values.
   * @param array $form
   *   The complete form array.
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   *   The current state of the form.
   */
  public function addBundleItemSelections($entity_type, OrderItemInterface $order_item, array $form, FormStateInterface $form_state) {
    $bundle_order_items = [];
    foreach ($form_state
      ->getValue('purchased_entity')[0]['bundle_items'] as $item => $selection) {

      // Cast values to string like OrderItem does for other fields.
      // Value type (string) and order are required when matching order items.
      // @see \Drupal\commerce_cart\OrderItemMatcher

      /** @var \Drupal\commerce_product\Entity\ProductVariationInterface $variation */
      $variation = $this->variationStorage
        ->load($selection['variation']);

      /** @var  \Drupal\commerce_product_bundle\Entity\BundleItemInterface $bundle_item */
      $bundle_item = $selection['bundle_item'];
      $bundle_order_item = $this->bundleItemOrderItemStorage
        ->create([
        'title' => $bundle_item
          ->getTitle(),
        'bundle_item' => $bundle_item,
        'purchased_entity' => $variation,
        'unit_price' => $bundle_item
          ->getUnitPrice(),
        'quantity' => (string) $selection['qty'],
      ]);
      $bundle_order_items[] = $bundle_order_item;
    }
    $order_item
      ->set('bundle_item_order_items', $bundle_order_items);
  }

}

Members

Namesort descending Modifiers Type Description Overrides
AllowedTagsXssTrait::allowedTags public function Returns a list of tags allowed by AllowedTagsXssTrait::fieldFilterXss().
AllowedTagsXssTrait::displayAllowedTags public function Returns a human-readable list of allowed tags for display in help texts.
AllowedTagsXssTrait::fieldFilterXss public function Filters an HTML string to prevent XSS vulnerabilities.
DependencySerializationTrait::$_entityStorages protected property An array of entity type IDs keyed by the property name of their storages.
DependencySerializationTrait::$_serviceIds protected property An array of service IDs keyed by property name used for serialization.
DependencySerializationTrait::__sleep public function 1
DependencySerializationTrait::__wakeup public function 2
MessengerTrait::$messenger protected property The messenger. 29
MessengerTrait::messenger public function Gets the messenger. 29
MessengerTrait::setMessenger public function Sets the messenger.
PluginBase::$configuration protected property Configuration information passed into the plugin. 1
PluginBase::$pluginDefinition protected property The plugin implementation definition. 1
PluginBase::$pluginId protected property The plugin_id.
PluginBase::DERIVATIVE_SEPARATOR constant A string which is used to separate base plugin IDs from the derivative ID.
PluginBase::getBaseId public function Gets the base_plugin_id of the plugin instance. Overrides DerivativeInspectionInterface::getBaseId
PluginBase::getDerivativeId public function Gets the derivative_id of the plugin instance. Overrides DerivativeInspectionInterface::getDerivativeId
PluginBase::getPluginDefinition public function Gets the definition of the plugin implementation. Overrides PluginInspectionInterface::getPluginDefinition 3
PluginBase::getPluginId public function Gets the plugin_id of the plugin instance. Overrides PluginInspectionInterface::getPluginId
PluginBase::isConfigurable public function Determines if the plugin is configurable.
PluginSettingsBase::$defaultSettingsMerged protected property Whether default settings have been merged into the current $settings.
PluginSettingsBase::$thirdPartySettings protected property The plugin settings injected by third party modules.
PluginSettingsBase::calculateDependencies public function Calculates dependencies for the configured plugin. Overrides DependentPluginInterface::calculateDependencies 6
PluginSettingsBase::defaultSettings public static function Defines the default settings for this plugin. Overrides PluginSettingsInterface::defaultSettings 42
PluginSettingsBase::getSetting public function Returns the value of a setting, or its default value if absent. Overrides PluginSettingsInterface::getSetting
PluginSettingsBase::getSettings public function Returns the array of settings, including defaults for missing settings. Overrides PluginSettingsInterface::getSettings
PluginSettingsBase::getThirdPartyProviders public function Gets the list of third parties that store information. Overrides ThirdPartySettingsInterface::getThirdPartyProviders
PluginSettingsBase::getThirdPartySetting public function Gets the value of a third-party setting. Overrides ThirdPartySettingsInterface::getThirdPartySetting
PluginSettingsBase::getThirdPartySettings public function Gets all third-party settings of a given module. Overrides ThirdPartySettingsInterface::getThirdPartySettings
PluginSettingsBase::mergeDefaults protected function Merges default settings values into $settings.
PluginSettingsBase::onDependencyRemoval public function Informs the plugin that some configuration it depends on will be deleted. Overrides PluginSettingsInterface::onDependencyRemoval 3
PluginSettingsBase::setSetting public function Sets the value of a setting for the plugin. Overrides PluginSettingsInterface::setSetting
PluginSettingsBase::setSettings public function Sets the settings for the plugin. Overrides PluginSettingsInterface::setSettings
PluginSettingsBase::setThirdPartySetting public function Sets the value of a third-party setting. Overrides ThirdPartySettingsInterface::setThirdPartySetting
PluginSettingsBase::unsetThirdPartySetting public function Unsets a third-party setting. Overrides ThirdPartySettingsInterface::unsetThirdPartySetting
ProductBundleItemsWidget::$attributeFieldManager protected property The attribute field manager.
ProductBundleItemsWidget::$attributeStorage protected property The product attribute storage.
ProductBundleItemsWidget::addBundleItemSelections public function Entity builder: updates the order item with the bundle item selections.
ProductBundleItemsWidget::create public static function Creates an instance of the plugin. Overrides ProductBundleWidgetBase::create
ProductBundleItemsWidget::formElement public function Returns the form for a single field widget. Overrides WidgetInterface::formElement
ProductBundleItemsWidget::getAttributeValues protected function Gets the attribute values of a given set of variations.
ProductBundleItemsWidget::getBundleItemForm private function Gets the child form element for a given bundle item.
ProductBundleItemsWidget::getItemAttributeInfo protected function Gets the attribute information for the selected product variation.
ProductBundleItemsWidget::selectVariationFromUserInput protected function Selects a product variation from user input.
ProductBundleItemsWidget::__construct public function Constructs a new ProductBundleItemsWidget object. Overrides ProductBundleWidgetBase::__construct
ProductBundleWidgetBase::$bundleItemOrderItemStorage protected property The bundle item order item storage.
ProductBundleWidgetBase::$bundleItemStorage protected property The product bundle item storage.
ProductBundleWidgetBase::$productStorage protected property The product storage.
ProductBundleWidgetBase::$variationStorage protected property The product variation storage.
ProductBundleWidgetBase::ajaxRefresh public static function #ajax callback: Replaces the rendered fields on variation change.
ProductBundleWidgetBase::isApplicable public static function Returns if the widget can be used for the provided field. Overrides WidgetBase::isApplicable
ProductBundleWidgetBase::massageFormValues public function Massages the form values into the format expected for field values. Overrides WidgetBase::massageFormValues
StringTranslationTrait::$stringTranslation protected property The string translation service. 1
StringTranslationTrait::formatPlural protected function Formats a string containing a count of items.
StringTranslationTrait::getNumberOfPlurals protected function Returns the number of plurals supported by a given language.
StringTranslationTrait::getStringTranslation protected function Gets the string translation service.
StringTranslationTrait::setStringTranslation public function Sets the string translation service to use. 2
StringTranslationTrait::t protected function Translates a string to the current language or to a given language.
WidgetBase::$fieldDefinition protected property The field definition.
WidgetBase::$settings protected property The widget settings. Overrides PluginSettingsBase::$settings
WidgetBase::addMoreAjax public static function Ajax callback for the "Add another item" button.
WidgetBase::addMoreSubmit public static function Submission handler for the "Add another item" button.
WidgetBase::afterBuild public static function After-build handler for field elements in a form.
WidgetBase::errorElement public function Assigns a field-level validation error to the right widget sub-element. Overrides WidgetInterface::errorElement 8
WidgetBase::extractFormValues public function Extracts field values from submitted form values. Overrides WidgetBaseInterface::extractFormValues 2
WidgetBase::flagErrors public function Reports field-level validation errors against actual form elements. Overrides WidgetBaseInterface::flagErrors 2
WidgetBase::form public function Creates a form element for a field. Overrides WidgetBaseInterface::form 3
WidgetBase::formMultipleElements protected function Special handling to create form elements for multiple values. 1
WidgetBase::formSingleElement protected function Generates the form element for a single copy of the widget.
WidgetBase::getFieldSetting protected function Returns the value of a field setting.
WidgetBase::getFieldSettings protected function Returns the array of field settings.
WidgetBase::getFilteredDescription protected function Returns the filtered field description.
WidgetBase::getWidgetState public static function Retrieves processing information about the widget from $form_state. Overrides WidgetBaseInterface::getWidgetState
WidgetBase::getWidgetStateParents protected static function Returns the location of processing information within $form_state.
WidgetBase::handlesMultipleValues protected function Returns whether the widget handles multiple values.
WidgetBase::isDefaultValueWidget protected function Returns whether the widget used for default value form.
WidgetBase::settingsForm public function Returns a form to configure settings for the widget. Overrides WidgetInterface::settingsForm 16
WidgetBase::settingsSummary public function Returns a short summary for the current widget settings. Overrides WidgetInterface::settingsSummary 15
WidgetBase::setWidgetState public static function Stores processing information about the widget in $form_state. Overrides WidgetBaseInterface::setWidgetState