protected function ProductBundleItemsWidget::getItemAttributeInfo in Commerce Product Bundle 8
Gets the attribute information for the selected product variation.
Parameters
\Drupal\commerce_product\Entity\ProductVariationInterface $selected_variation: The selected product variation.
\Drupal\commerce_product\Entity\ProductVariationInterface[] $variations: The available product variations.
Return value
array[] The attribute information, keyed by field name.
1 call to ProductBundleItemsWidget::getItemAttributeInfo()
- ProductBundleItemsWidget::getBundleItemForm in src/
Plugin/ Field/ FieldWidget/ ProductBundleItemsWidget.php - Gets the child form element for a given bundle item.
File
- src/
Plugin/ Field/ FieldWidget/ ProductBundleItemsWidget.php, line 317
Class
- ProductBundleItemsWidget
- Plugin implementation of the 'commerce_product_bundle_items' widget.
Namespace
Drupal\commerce_product_bundle\Plugin\Field\FieldWidgetCode
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;
}