How to add field value while creating a simple product Programmatically in Magento 2?
-
14-04-2021 - |
Question
I have successfully created simple product Programmatically using magento 2.
But i have created a filed in back end and add that in product but how to fill that data when creating a product.
I have created my product by
$product = $this->productFactory->create();
$product->setSku($productsku);
$product->setName($productname);
$product->setDescription($productname."Description3");
$product->setShortDescription($productname."Short Description3");
$product->setWebsiteIds([1]);
$categories = ["3"];
$product->setCategoryIds($categories);
$product->setWeight(1);
$product->setTypeId(\Magento\Catalog\Model\Product\Type::TYPE_SIMPLE);
$product->setVisibility(\Magento\Catalog\Model\Product\Visibility::VISIBILITY_BOTH); // To make product visible in both catalog,search
$product->setPrice($p);
$product->setAttributeSetId(4); // Attribute set for products
$product->setStatus(\Magento\Catalog\Model\Product\Attribute\Source\Status::STATUS_ENABLED);
$product->setUrlKey($productsku);
$product->setStockData(
array(
'use_config_manage_stock' => 0,
'manage_stock' => 1,
'is_in_stock' => 1,
'qty' => 1
)
);
$product = $this->productRepository->save($product);
$product->save();
Like i have to add some custom data while creating a product Programmatically.How to do that ?
Any Help is appreciated.
Solution
Custom attributes values in magento 2 can be set and retrieved by
Getting Value getCustomAttribute('myattribute')->getValue() / getMyattribute()
Setting Value setCustomAttribute('myattribute', $value); / setMyattribute($value)
Licensed under: CC-BY-SA with attribution
Not affiliated with magento.stackexchange