Skip to content

Attribute Option label not updating in Magento2

I created a setup Patch file to update the label of attribute options.

Tried below code

CustomVendorSetupPatchDataUpdateColorAttributeOptions.php

  <?php

  namespace CustomVendorSetupPatchData;

  use MagentoEavApiAttributeRepositoryInterface;
  use MagentoEavApiDataAttributeOptionLabelInterfaceFactory;
  use MagentoEavApiDataAttributeOptionInterface;
  use MagentoEavModelConfig;
  use MagentoFrameworkSetupPatchDataPatchInterface;
  use MagentoFrameworkSetupModuleDataSetupInterface;
  use MagentoFrameworkAppResourceConnection;

class UpdateColorAttributeOptions implements DataPatchInterface
 {
  private $moduleDataSetup;
  private $eavConfig;
  private $attributeRepository;
  private $optionLabelFactory;
  private $resource;

  public function __construct(
    ModuleDataSetupInterface $moduleDataSetup,
    Config $eavConfig,
    AttributeRepositoryInterface $attributeRepository,
    AttributeOptionLabelInterfaceFactory $optionLabelFactory,
    ResourceConnection $resource
) {
    $this->moduleDataSetup = $moduleDataSetup;
    $this->eavConfig = $eavConfig;
    $this->attributeRepository = $attributeRepository;
    $this->optionLabelFactory = $optionLabelFactory;
    $this->resource = $resource;
}

public function apply()
{
    
    $this->moduleDataSetup->getConnection()->startSetup();

    // Define attribute code and the options you want to update
    $attributeCode = 'color'; // Replace with your attribute code
    $optionsToUpdate = [
        'Red Color' => 'Red',
        'Green Color' => 'Green',
    ];

    // Load the attribute
    $attribute = $this->eavConfig->getAttribute('catalog_product', $attributeCode);

   
    $options = $attribute->getOptions();
   
    foreach ($options as $option) {
        foreach ($optionsToUpdate as $oldLabel => $newLabel) {
            if ($option->getLabel() === $oldLabel) {
                /** @var AttributeOptionInterface $option */
                $option->setLabel($newLabel);
                $attribute->setOptions([$option]); 
                $this->attributeRepository->save($attribute);
            }
        }
    }


    $this->moduleDataSetup->getConnection()->endSetup();
}

public static function getDependencies()
{
    return [];
}

   public function getAliases()
   {
    return [];
   }
}

The above code is not updating the labels of attribute options, Please someone check and let me know where I am doing wrong.

Thanks!