Skip to content

Instantly share code, notes, and snippets.

@nevvermind
Last active April 7, 2021 09:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save nevvermind/155952b0b01773f4b42f to your computer and use it in GitHub Desktop.
Save nevvermind/155952b0b01773f4b42f to your computer and use it in GitHub Desktop.
Saving an EAV Product attribute via the extensions mechanism
<?php
/** @var \Magento\Catalog\Api\ProductRepositoryInterface $productRepo */
$productRepo = $objManager->get(\Magento\Catalog\Api\ProductRepositoryInterface::class);
/** @var \Magento\Catalog\Api\Data\ProductInterface $productData */
$product = $productRepo->get('some_sku');
/** @var \Magento\Catalog\Api\Data\ProductExtensionInterface $ext */
$ext = $product->getExtensionAttributes();
/**
* At this point, $ext has only "stock_item" as an extension attribute,
* because it was added manually on load: http://git.io/vW0xh
*
* "stock_item" seems to be a complex, extension attribute.
* That is - it does not exist as an EAV attribute.
* It's added here: http://git.io/vW0xD
*
* Because I fancy auto-completion, I created an extension attribute - "foo_bar" -
* mapped to an actual EAV product attribute (aka created via "addAttribute()"):
*
* // somewhere, in an "extension_attributes.xml" file
* <extension_attributes for="Magento\Catalog\Api\Data\ProductInterface">
* <attribute code="foo_bar" type="int" />
* </extension_attributes>
*/
// normally, we would do $product->setCustomAttribute('foo_bar', 3);
$ext->setFooBar(3); // we get auto-completion here. nice!
// do we always have to do this?
$product->setExtensionAttributes($ext);
// this actually saves my EAV attribute correctly, depending on the store I'm in
$productRepo->save($product);
@nevvermind
Copy link
Author

The Product repository being the one converting our extension attributes to the $data array (same as doing $productModel->setData($data)).

So I guess any logic outside the Repository object won't have this behaviour by default.

@LifeAsBook
Copy link

hi nevvermind, why the CustomAttributesDataInterface extends ExtensibleDataInterface, CUSTOMER ATTRIBUTE is sub of Extension attributes?

@adragus-inviqa
Copy link

@LifeAsBook - yeah, I guess. Why? Also, it's customer attribute data, which is extensible.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment