I need to add product attribute value to product during import product programatically how to add this in magento 2? can anyone advise me?
4 Answers
Upload from the default CSV generated by Magento Yes you need to fill all your custom attributes into the single column named additional_attributes_code.
Just simply put all your custom attribute in following way into the column with name additional_attributes_code into your imported CSV file.
custom_attribute_code_1="Value_1",custom_attribute_code_2="Value_2",custom_attribute_code_3="Value_3",custom_attribute_code_4="Value_4"
After this simply upload your CSV file.
-
yes but this lot of manual work,i need to acheive this in programmatically any idea to this Commented Jun 17, 2020 at 6:12
If you want to import product attributes programmatically, then you can create a file in the bin folder to run from CLI. You can do as below code, but you have to modify it as your needs. This filename was import, and will run as php bin/import. Remember this file doesn't have an ext name like .php or .phtml as it is a script file.
#!/usr/bin/env php
<?php
if (PHP_SAPI !== 'cli') {
echo 'bin/import must be run as a CLI application';
exit(1);
}
echo "Enter Attribute Set Id: ";
$handle = fopen ("php://stdin","r");
$attributeSetId = fgets($handle);
echo "Enter Website Id: ";
$handle = fopen ("php://stdin","r");
$websiteId = fgets($handle);
echo "Enter Visibility Id: ";
$handle = fopen ("php://stdin","r");
$visibilityId = fgets($handle);
use Magento\Framework\App\Bootstrap;
require __DIR__ . '/../app/bootstrap.php';
$bootstrap = Bootstrap::create(BP, $_SERVER);
$objectManager = $bootstrap->getObjectManager();
$state = $objectManager->get('Magento\Framework\App\State');
$state->setAreaCode('frontend');
$file_handle = fopen("pub/media/import/Suppliers_Product.csv", "r");
echo "Product Import started";
$row = null;
$data = [];
while (!feof($file_handle) ) {
$line_of_text = fgetcsv($file_handle, 1024);
if($row == null){
$row = $line_of_text;
continue;
} else {
$data = array_combine($row, $line_of_text);
}
$name = trim($data['descript']);
if(trim($data['sku']) == 0){
$sku = mt_rand();
}else{
$sku = trim($data['sp_sku']);
}
$price = trim($data['trade_prc']);
if(trim($data['commodity_code']) == 'NULL'){
$commodity_code = '';
}else{
$commodity_code = trim($data['commodity_code']);
}
if(trim($data['cost']) == 'NULL'){
$cost = '';
} else {
$cost = trim($data['cost']);
}
if (strpos(trim($data['stock']), '-') !== false) {
$stock = 0;
} else {
$stock = trim($data['stock']);
}
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$product = $objectManager->get('Magento\Catalog\Model\Product');
if($product->getIdBySku($sku)) {
$products_already_present[] = array_combine($row, $line_of_text);
continue;
}else{
$_product = $objectManager->create('Magento\Catalog\Model\Product');
$_product->setName($name);
$_product->setTypeId('simple');
$_product->setAttributeSetId(trim($attributeSetId));
$_product->setSku($sku);
$_product->setWebsiteIds(array(trim($websiteId)));
$_product->setVisibility(trim($visibilityId));
$_product->setPrice($price);
$_product->setData('cost', $cost);
$_product->setData('commodity_code', $commodity_code);
$_product->setStockData(array(
'use_config_manage_stock' => 0,
'manage_stock' => 1,
'min_sale_qty' => 1,
'max_sale_qty' => '',
'is_in_stock' => 1,
'use_config_notify_stock_qty' => 1,
'qty' => $stock
)
);
$_product->save();
echo'.';
}
}
-
-
I need to update this after product import completed then update the attribute of all products Commented Jun 17, 2020 at 7:12
-
This is only for products that are already added in Magento and we update attributes. To create Products with attributes you have to change code. Commented Jun 17, 2020 at 7:20
-
-
You need to create product pragmatically like this .
https://www.mageplaza.com/devdocs/magento-2-create-product-programmatically.html
And you can assign your customattribute like this. Say for example you have custom attribute having code "custom_attribute1". than write like below code.
$objectManager = \Magento\Framework\App\ObjectManager::getInstance(); // instance of object manager
$product = $objectManager->create('\Magento\Catalog\Model\Product');
$product->setCustomAttribute1("yourvalue");
$product->save();
If you want to do after import than perform following steps.
If you want to $productobj after saving product from backend then you can easily use catalog_product_save_after event.
I am assuming that you already know how to create a module in M2.
Put this events.xml in below path
app\code\NAMESPACE\MODULENAME\etc\adminhtml
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd">
<event name="catalog_product_save_after">
<observer name="test_name" instance="NAMESPACE\MODULENAME\Observer\ProductUpdateAttribute" />
</event>
</config>
Add following code to PRoductUpdateAttribute.php file
<?php
namespace NAMESPACE\MODULENAME\Observer;
use Magento\Framework\Event\ObserverInterface;
class PRoductUpdateAttribute implements ObserverInterface
{
public function execute(\Magento\Framework\Event\Observer $observer)
{
$product = $observer->getProduct(); // product object
$product->setCustomAttribute1('valuehere');
$product->save();
}
}
-
-
-
-
-
Hi need to update attribute after product import any event.. Commented Jun 17, 2020 at 7:14
add this additional attribute code before
$rowData = $this->_prepareRowForDb($rowData);
file path
/vendor/magento/module-import-export/Model/Import/Entity/AbstractEntity.php
Function
protected function _saveValidatedBunches()
{
$source = $this->_getSource();
$currentDataSize = 0;
$bunchRows = [];
$startNewBunch = false;
$nextRowBackup = [];
$maxDataSize = $this->_resourceHelper->getMaxDataSize();
$bunchSize = $this->_importExportData->getBunchSize();
$skuSet = [];
$source->rewind();
$this->_dataSourceModel->cleanBunches();
while ($source->valid() || $bunchRows) {
if ($startNewBunch || !$source->valid()) {
$this->_dataSourceModel->saveBunch($this->getEntityTypeCode(), $this->getBehavior(), $bunchRows);
$bunchRows = $nextRowBackup;
$currentDataSize = strlen($this->getSerializer()->serialize($bunchRows));
$startNewBunch = false;
$nextRowBackup = [];
}
if ($source->valid()) {
try {
$rowData = $source->current();
if (array_key_exists('sku', $rowData)) {
$skuSet[$rowData['sku']] = true;
}
} catch (\InvalidArgumentException $e) {
$this->addRowError($e->getMessage(), $this->_processedRowsCount);
$this->_processedRowsCount++;
$source->next();
continue;
}
$this->_processedRowsCount++;
if ($this->validateRow($rowData, $source->key())) {
// add row to bunch for save
$pre_order_qty = $rowData['qty'];
if($rowData['additional_attributes'])
{
if($rowData['additional_attributes'] != '')
{
$rowData['additional_attributes'] = $rowData['additional_attributes'].',preorder_custom_qty='.$pre_order_qty;
}
else
{
$rowData['additional_attributes'] = 'preorder_custom_qty='.$pre_order_qty;
}
}
else
{
$rowData['additional_attributes'] = 'preorder_custom_qty='.$pre_order_qty;
}
$rowData = $this->_prepareRowForDb($rowData);
$rowSize = strlen($this->jsonHelper->jsonEncode($rowData));
$isBunchSizeExceeded = $bunchSize > 0 && count($bunchRows) >= $bunchSize;
if ($currentDataSize + $rowSize >= $maxDataSize || $isBunchSizeExceeded) {
$startNewBunch = true;
$nextRowBackup = [$source->key() => $rowData];
} else {
$bunchRows[$source->key()] = $rowData;
$currentDataSize += $rowSize;
}
}
$source->next();
}
}
$this->_processedEntitiesCount = (count($skuSet)) ? : $this->_processedRowsCount;
return $this;
}
the main code is
$pre_order_qty = $rowData['qty'];
if($rowData['additional_attributes'])
{
if($rowData['additional_attributes'] != '')
{
$rowData['additional_attributes'] = $rowData['additional_attributes'].',preorder_custom_qty='.$pre_order_qty;
}
else
{
$rowData['additional_attributes'] = 'preorder_custom_qty='.$pre_order_qty;
}
}
else
{
$rowData['additional_attributes'] = 'preorder_custom_qty='.$pre_order_qty;
}
$rowData = $this->_prepareRowForDb($rowData);