0

I am using magento 2.2.3, and created a dropdown attribute "wholeseler" in admin area with some attribute values. Now I want to update the "wholeseler" attribute value programmatically.

I am using below code but not working

<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);

use \Magento\Framework\App\Bootstrap;

include('app/bootstrap.php');
$bootstraps = Bootstrap::create(BP, $_SERVER);
$object_Manager = $bootstraps->getObjectManager();
$app_state = $object_Manager->get('\Magento\Framework\App\State');
$app_state->setAreaCode('frontend');

// Instance of object manager
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$productFactory = $objectManager->create('Magento\Catalog\Model\ProductFactory');

$productResourceModelFactory = $objectManager->create('Magento\Catalog\Model\ResourceModel\ProductFactory');

$productId = "84";

$product = $productFactory->create()->load($productId);
$product->setWhol("rub");
$product->save();

$productResource = $productResourceModelFactory->create();
$productResource->saveAttribute($product, 'whol'); 
echo "whol added ".$product->getId()."\n";

Please share any alternate solution that work for save the attribute value.

2 Answers 2

0
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$eavConfig = $objectManager->get('\Magento\Eav\Model\Config');
$attribute = $eavConfig->getAttribute('catalog_product', 'your_attribute_code');
$options = $attribute->getSource()->getAllOptions();
foreach($options as $option) {
    if($option['label'] == "your text"){
        // $option['value'] - your value
    }
}
3
  • Please share code example if you have for M2? Apr 16, 2018 at 6:13
  • answer was updated Apr 16, 2018 at 6:26
  • but this only for example, it can be not the best way to do that, i copied this from another same questions... look in the model, may be you can get "integer" values withour listing of all... Apr 16, 2018 at 6:28
0
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$eavConfig = $objectManager->get('\Magento\Eav\Model\Config');
$attribute = $eavConfig->getAttribute('catalog_product', 'your_attribute_code');
$options = $attribute->getSource()->getAllOptions();
$value = '';
foreach($options as $option) {
    if($option['label'] == "your text"){
        $value = $option['value'];
    }
}
$objectManager = \Magento\Framework\App\ObjectManager::getInstance(); // instance of object manager
$product = $objectManager->create('\Magento\Catalog\Model\Product');
$prod = $product->loadByAttribute('sku', 'sku');

$attr_code = 'your_attribute_code';
$prod->setCustomAttribute($attr_code, $value);
$prod->save();

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.