Magento – Setting attribute labels programmatically

attributeseavmagento-2.1upgrade-script

I'm trying to set labels for attributes for each language. For example I want to translate Price (in Stores > Attributes > Product > Price > Manage labels) for all the store views.
enter image description here

However, I can't seem to find a way to do this via UpgradeData.php. I don't want to directly inject with an SQL query. Looking for something like this, but it doesn't work:

if (version_compare($context->getVersion(), '0.0.xx') < 0) {
        $eavSetup = $this->eavSetupFactory->create(['setup' => $setup]);
        $attributeId = $eavSetup->getAttributeId('catalog_product', 'price');
        $options = [
            'values' => [
                'Dutch(NL)' => 'Prijs',
            ],
            'attribute_id' => $attributeId,
        ];
        $eavSetup->addAttributeOption($options);
    }

Best Answer

You can set the frontend labels with the following code in your UpgradeData or InstallData script:

    /** @var \Magento\Eav\Setup\EavSetup $eavSetup */
    $eavSetup = $this->eavSetupFactory->create(['setup' => $setup]);

    $attribute = $this->productAttributeRepository->get($attributeCode);
    $sourceModel = $attribute->getSourceModel();
    $frontendLabels = [
        $this->attributeFrontendLabelFactory->create()
            ->setStoreId(1)
            ->setLabel('Label 1'),
        $this->attributeFrontendLabelFactory->create()
            ->setStoreId(2)
            ->setLabel('Label 2'),
    ];
    $attribute->setFrontendLabels($frontendLabels);
    $this->productAttributeRepository->save($attribute);

    if ($sourceModel !== null) {
        $eavSetup->updateAttribute(
            \Magento\Catalog\Model\Product::ENTITY,
            $attributeCode,
            \Magento\Catalog\Api\Data\EavAttributeInterface::SOURCE_MODEL,
            $sourceModel
        ); // this is needed as the attribute repository throws away the source model while saving in Magento 2.2.5
    }

$this->eavSetupFactory is of type \Magento\Eav\Setup\EavSetupFactory.

$this->productAttributeRepository is of type \Magento\Catalog\Api\ProductAttributeRepositoryInterface.

$this->attributeFrontendLabelFactory is of type \Magento\Eav\Api\Data\AttributeFrontendLabelInterfaceFactory.

You should inject them via Dependency Injection in the constructor.