0

I have created a script file to update the multi select attribute for the products

here is my code

 <?php

 error_reporting(E_ALL);
 use \Magento\Framework\App\Bootstrap;
 require __DIR__ . '/app/bootstrap.php';
 $bootstrap = Bootstrap::create(BP, $_SERVER);
 $obj = $bootstrap->getObjectManager(); 
 $state = $obj->get('Magento\Framework\App\State');
 $state->setAreaCode('frontend');

 $resource = $obj->get('Magento\Framework\App\ResourceConnection');
 $connection = $resource->getConnection();
 $sql = "SELECT `e`.*  FROM `catalog_product_entity` AS `e` WHERE (`e`.`attribute_set_id` = '19') limit 3";
 $result = $connection->query($sql);
 $resultCollection = $result->fetchAll();
 $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
 foreach($resultCollection as $item){
  $productId = $item['entity_id'];  
  $product = $objectManager->get('Magento\Catalog\Model\ProductFactory')->create()->load($productId);
  $attrCode = 'pod_paper_size';
  $sourceModel = $product->getResource()->getAttribute('pod_paper_size')->getSource();
  $valuesText = explode(',', 'Extra_Small,Medium,Small,Large');

  $valuesIds = array_map(array($sourceModel, 'getOptionId'), $valuesText);

  $product->setData('pod_paper_size', $valuesIds);
  $product->setVisibility(4);
  $product->save();

}

Can anyone update me what is the correct code to update the multi-select attribute value pro grammatically, Thanks in Advance!!

2
  • Cant You just use Magento update script ? Commented May 12, 2020 at 17:48
  • @KonradSiamro,okay please update it as answer Commented May 13, 2020 at 5:46

1 Answer 1

0

If it is one time script, You should use Magento Update Script.
Instead of using sql, You can get product attached to specific atribut set using Search criteria https://alanstorm.com/magento_2_understanding_object_repositories/

Instead of using objectManager, use constructor.

On product You should be able to set values for multiselect as array or string ( imploded array) - using values Id.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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