1

I have created custom attribute named my_shipping_charge in magento 2 programmatically. I set default value '0' for this attribute. It works fine when I create new product. But what if I want to set this attribute for already created product what should I do.? Please help me to solve this problem.

Khooshbu Patel
  • 80
  • 1
  • 12
  • 1
    Hi let us continue this discussion in chat https://chat.stackoverflow.com/rooms/188325/learn-php – Nimesh Patel Feb 13 '19 at 06:34
  • please give answer for this question https://stackoverflow.com/questions/54365145/magento-reindexing-cli-command-after-set-variable-path-php-is-not-recognized @nimesh – Khooshbu Patel Feb 13 '19 at 12:13

1 Answers1

4

For already created products we should have to update manually, if the product collection is larger can run a file in root. In this root file we can load all the product collection and set the custom attribute value for all the products and save it.

custom file in root folder will be like below :

<?php
use \Magento\Framework\App\Bootstrap;
require __DIR__ . "/app/bootstrap.php";
$bootstrap = Bootstrap::create(BP, $_SERVER);
$objectManager = $bootstrap->getObjectManager();
$instance = \Magento\Framework\App\ObjectManager::getInstance();
$state = $objectManager->get('\Magento\Framework\App\State');
$state->setAreaCode('frontend');
$product_collections = $instance ->get('\Magento\Catalog\Model\ResourceModel\Product\CollectionFactory');
$collections = $product_collections->create();
$shippingCharge = "custom value";
foreach ($collections as $product) {
    $product->setMyShippingCharge($shippingCharge);
    $product->save();
}
?>

$shippingCharge will be the custom value have to update. Run the root file in terminal and reindex. And check from admin panel

Nayana Chandran
  • 1,416
  • 1
  • 16
  • 30
  • 1
    I also found another way to update attribute, using import. I have created a CSV file set attribute value for each product and import that file. It's also working. – Khooshbu Patel Feb 13 '19 at 05:09
  • 1
    Right idea, but altering catalog CSV file is a risk, be careful if having multi-store or website. – Nayana Chandran Feb 13 '19 at 06:53