Añadir atributos de producto de forma dinámica

Puede ampliar los atributos de producto sin registrarlos en Adobe Commerce creando un complemento para agregar los atributos durante el proceso de sincronización de datos.

NOTE
La mejor manera de ampliar los atributos del producto es agregarlos a Adobe Commerce where you can configure and manage them from the Commerce Admin. Only add them dynamically if you need them solely for Commerce storefront services and do not want to register them in Adobe Commerce. You also have the option to manage custom attributes using API Mesh con Catalog Service para extender el esquema Catalog Service GraphQL.

Añadir atributos del producto

Cree un complemento que agregue customer_attribute a la clase Magento\CatalogDataExporter\Model\Provider\Product\Attributes.

  1. Actualice el archivo de configuración de inyección de dependencia (di.xml) para definir el complemento.

    code language-xml
    <type name="Magento\CatalogDataExporter\Model\Provider\Product\Attributes">
      <plugin name="product_customer_attributes" type="Vendor\CatalogDataExporter\Model\Plugin\AddAttribute"/>
    </type>
    
  2. Cree el complemento.

    code language-php
     <?php
     declare(strict_types=1);
    
     namespace Vendor\CatalogDataExporter\Model\Plugin;
    
     use Magento\CatalogDataExporter\Model\Provider\Product\Attributes;
    
     class AddAttribute {
    
          /**
           * @param Attributes $subject
           * @param array $result
           * @param $arguments
           * @return array
           * @throws \Zend_Db_Statement_Exception
           */
           public function afterGet(Attributes $subject, array $result, $arguments): array
           {
               $additionalAttributes = [];
               $attributeCode = 'customer_attribute';
               foreach ($result as $product) {
                   if (!isset($product['productId']) || !isset($product['storeViewCode'])) {
                       continue;
                   }
                   // HINT: if needed, do filtration by "storeViewCode" and or "productId"
    
                   $productId = $product['productId'];
                   $storeViewCode = $product['storeViewCode'];
    
                   $newKey = \implode('-', [$product['storeViewCode'], $product['productId'], $attributeCode]);
                   if (isset($additionalAttributes[$newKey])) {
                       continue;
                   }
                   $additionalAttributes[$newKey] = [
                       'productId' => $productId,
                       'storeViewCode' => $storeViewCode,
                       'attributes' => [
                           'attributeCode' => $attributeCode,
                           // provide single or multiple values for the attribute
                           'value' => [
                               rand(1, 42)
                           ]
                       ]
                   ];
    
               }
    
               return array_merge($result, $additionalAttributes);
           }
     }
    

    Después de agregar el complemento, los cambios se sincronizan con los servicios de tienda conectados durante la siguiente sincronización programada. Para enviar las actualizaciones inmediatamente, utilice el siguiente comando CLI para iniciar el proceso de sincronización manualmente.

    code language-shell
    bin/magento saas:resync --feed=products
    

Declarar metadatos de atributos de producto personalizados

Si crea dinámicamente un atributo de producto personalizado y desea utilizarlo para su visualización, búsqueda o filtrado en los servicios de tienda, agregue los metadatos del atributo de producto para configurar el comportamiento de la tienda.

  1. Actualice el archivo de configuración de inyección de dependencia (di.xml) para definir el complemento para los metadatos de atributos del producto.

    code language-xml
    <type name="Magento\CatalogDataExporter\Model\Provider\ProductMetadata">
      <plugin name="product_customer_attributes_metadata" type="Vendor\CatalogDataExporter\Model\Plugin\AddAttributeMetadata"/>
    </type>
    
  2. Cree el complemento para el siguiente proveedor Magento\CatalogDataExporter\Model\Provider\ProductMetadata.

    Compruebe ProductAttributeMetadata en vendor/magento/module-catalog-data-exporter/etc/et_schema.xml los campos obligatorios.

    code language-php
     <?php
     declare(strict_types=1);
    
     namespace Vendor\CatalogDataExporter\Model\Plugin;
    
     use Magento\CatalogDataExporter\Model\Provider\ProductMetadata;
    
     class AddAttributeMetadata {
    
          /**
           * @param ProductMetadata $subject
           * @param array $result
           * @param $arguments
           * @return array
           * @throws \Zend_Db_Statement_Exception
           */
          public function afterGet(ProductMetadata $subject, array $result, $arguments): array
          {
               $result[] = [
                 'id' => '123',
                 // provide storeCode, websiteCode and storeViewCode applicable for your AC instance
                 'storeCode' => 'default',
                 'websiteCode' => 'base',
                 'storeViewCode' => 'default',
                 // specify the customer attribute code - should be the same as used in the products attributes plugin
                 'attributeCode' => 'customer_attribute',
                 // only product attributes are supported
                 'attributeType' => 'catalog_product',
                 // specify the data type
                 'dataType' => 'int',
                 'multi' => false,
                 'label' => 'Customer Attribute',
                 'frontendInput' => 'select',
                 'required' => false,
                 'unique' => false,
                 'global' => true,
                 'visible' => true,
                 'searchable' => true,
                 'filterable' => true,
                 // This value must be set to true to export it to the storefront services
                 'visibleInCompareList' => true,
                 'visibleInListing' => true,
                 'sortable' => true,
                 'visibleInSearch' => true,
                 'filterableInSearch' => true,
                 'searchWeight' => 1.0,
                 'usedForRules' => true,
                 'boolean' => false,
                 'systemAttribute' => false,
                 'numeric' => false,
                 // specify the list of attribute options
                 'attributeOptions' => [
                     'option1',
                     'option2',
                     'option3'
                 ]
              ];
    
               return $result;
          }
       }
    

    Después de agregar el complemento, los cambios se sincronizan con los servicios de tienda conectados durante la siguiente sincronización programada. Para enviar las actualizaciones inmediatamente, utilice el siguiente comando CLI para iniciar el proceso de sincronización manualmente.

    code language-shell
    bin/magento saas:resync --feed=productAttributes
    
recommendation-more-help
commerce-help-data-export