You are here

public function ProductAttributeFieldManager::createField in Commerce Core 8.2

Creates an attribute field for the given attribute.

Parameters

\Drupal\commerce_product\Entity\ProductAttributeInterface $attribute: The product attribute.

string $variation_type_id: The product variation type ID.

Overrides ProductAttributeFieldManagerInterface::createField

File

modules/product/src/ProductAttributeFieldManager.php, line 168

Class

ProductAttributeFieldManager
Default implementation of the ProductAttributeFieldManagerInterface.

Namespace

Drupal\commerce_product

Code

public function createField(ProductAttributeInterface $attribute, $variation_type_id) {
  $field_name = $this
    ->buildFieldName($attribute);
  $field_storage = FieldStorageConfig::loadByName('commerce_product_variation', $field_name);
  $field = FieldConfig::loadByName('commerce_product_variation', $variation_type_id, $field_name);
  if (empty($field_storage)) {
    $field_storage = FieldStorageConfig::create([
      'field_name' => $field_name,
      'entity_type' => 'commerce_product_variation',
      'type' => 'entity_reference',
      'cardinality' => 1,
      'settings' => [
        'target_type' => 'commerce_product_attribute_value',
      ],
      'translatable' => FALSE,
    ]);
    $field_storage
      ->save();
  }
  if (empty($field)) {
    $field = FieldConfig::create([
      'field_storage' => $field_storage,
      'bundle' => $variation_type_id,
      'label' => $attribute
        ->label(),
      'required' => TRUE,
      'settings' => [
        'handler' => 'default',
        'handler_settings' => [
          'target_bundles' => [
            $attribute
              ->id(),
          ],
        ],
      ],
      'translatable' => FALSE,
    ]);
    $field
      ->save();

    /** @var \Drupal\Core\Entity\Display\EntityFormDisplayInterface $form_display */
    $form_display = commerce_get_entity_display('commerce_product_variation', $variation_type_id, 'form');
    $form_display
      ->setComponent($field_name, [
      'type' => 'options_select',
      'weight' => $this
        ->getHighestWeight($form_display) + 1,
    ]);
    $form_display
      ->save();
    $this
      ->clearCaches();
  }
}