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.
asked Apr 13, 2018 at 7:06
Purushotam Sharma
1,6772 gold badges28 silver badges62 bronze badges
2 Answers 2
$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
}
}
answered Apr 16, 2018 at 6:09
Slava Yurthev
1681 silver badge11 bronze badges
-
Please share code example if you have for M2?Purushotam Sharma– Purushotam Sharma2018年04月16日 06:13:07 +00:00Commented Apr 16, 2018 at 6:13
-
answer was updatedSlava Yurthev– Slava Yurthev2018年04月16日 06:26:47 +00:00Commented 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...Slava Yurthev– Slava Yurthev2018年04月16日 06:28:38 +00:00Commented Apr 16, 2018 at 6:28
$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();
default