Change attribute scope programmatically in Magento 2 using UpgradeSchema

On by

less than 1 minute read

Had some trouble writing my UpgradeSchema to change attribute scope of existing attribute. I was using global instead of is_global flag inupdateAttribute(). Which is funny because global works when adding new attribute but not when updating attribute.

<?php

namespace Mage2\Module\Setup;

use Magento\Framework\Setup\SchemaSetupInterface;
use Magento\Framework\Setup\UpgradeSchemaInterface;
use Magento\Framework\Setup\ModuleContextInterface;
use Magento\Framework\Setup\ModuleDataSetupInterface;

class UpgradeSchema implements UpgradeSchemaInterface {

    private $eavSetupFactory;

    public function __construct(
        \Magento\Eav\Setup\EavSetupFactory $eavSetupFactory
    ) {
        $this->eavSetupFactory = $eavSetupFactory;
    }

    public function upgrade(SchemaSetupInterface $setup, ModuleContextInterface $context)
    {
        $setup->startSetup();
        if (version_compare($context->getVersion(), '0.1.15', '<')) {
            $this->upgradeVersionZeroOneFifteen();
        }
        $setup->endSetup();
    }

    private function upgradeVersionZeroOneFifteen(
        ModuleDataSetupInterface $setup,
        ModuleContextInterface $context
    ) {
        $eavSetup = $this->eavSetupFactory->create(['setup' => $setup]);
        $attributes = [
            'attribute_code_1',
            'attribute_code_2',
            'attribute_code_3'
        ];
        foreach ($attributes as $attribute) {
            $eavSetup->updateAttribute(
                \Magento\Catalog\Model\product::ENTITY,
                $attribute,
                'is_global',
                \Magento\Eav\Model\Entity\Attribute\ScopedAttributeInterface::SCOPE_STORE
            );
        }
    }
}