2

I am adding products programmatically in Magento 2. I want to recover all the manufacturers and test if it exists otherwise I want to create it.

How to recover all brands in magento2?

1

The manufacturer is a regular Magento EAV attribute of product entity. You can take all available values and labels using the following code snippet:

$om = \Magento\Framework\App\ObjectManager::getInstance();

/** @var \Magento\Catalog\Api\Data\ProductAttributeInterface $attribute */
$attribute = $om->get(\Magento\Catalog\Api\ProductAttributeRepositoryInterface::class)
    ->get('manufacturer');

foreach ($attribute->getOptions() as $option) {
     var_dump($option->getValue() . ' -> ' . $option->getLabel());
}

You can use the same repository class to save the modified attribute. Please use constructor dependency injection instead of a direct call to object manager in your code.

Also, you can do the same using WebApi:

<route url="/V1/products/attributes/:attributeCode" method="GET">
    <service class="Magento\Catalog\Api\ProductAttributeRepositoryInterface" method="get"/>
    <resources>
        <resource ref="Magento_Catalog::attributes_attributes" />
    </resources>
</route>
<route url="/V1/products/attributes" method="GET">
    <service class="Magento\Catalog\Api\ProductAttributeRepositoryInterface" method="getList" />
    <resources>
        <resource ref="Magento_Catalog::attributes_attributes" />
    </resources>
</route>
<route url="/V1/products/attributes" method="POST">
    <service class="Magento\Catalog\Api\ProductAttributeRepositoryInterface" method="save"/>
    <resources>
        <resource ref="Magento_Catalog::attributes_attributes" />
    </resources>
</route>
<route url="/V1/products/attributes/:attributeCode" method="PUT">
    <service class="Magento\Catalog\Api\ProductAttributeRepositoryInterface" method="save"/>
    <resources>
        <resource ref="Magento_Catalog::attributes_attributes" />
    </resources>
</route>
<route url="/V1/products/attributes/:attributeCode" method="DELETE">
    <service class="Magento\Catalog\Api\ProductAttributeRepositoryInterface" method="deleteById"/>
    <resources>
        <resource ref="Magento_Catalog::attributes_attributes" />
    </resources>
</route>
  • thank you for your explanation this is exactly what I want. – lisa Dec 15 '17 at 13:15

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.