Last active
April 7, 2021 09:57
-
-
Save nevvermind/155952b0b01773f4b42f to your computer and use it in GitHub Desktop.
Saving an EAV Product attribute via the extensions mechanism
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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); | |
hi nevvermind, why the CustomAttributesDataInterface extends ExtensibleDataInterface, CUSTOMER ATTRIBUTE is sub of Extension attributes?
@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
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.