Magento 2 – Import Bulk Products with Custom Attribute

bulkcustommagento2product

I have created 1 custom attribute (current_user_id) and saving value when product is saved.
I have usecatalog_product_save_before event that save value for my custom attribute(current_user_id). code is

public function execute(\Magento\Framework\Event\Observer $observer)
    {
        $_product = $observer->getProduct();  // you will get product object
        $current_users=$this->authSession->getUser();
        $current_admin_id=$current_users->getData('user_id');
        $_product->setCurrentUserId($current_admin_id) ;
    }

It work perfect for add single product.

But now I want to add bulk products How this possible for import bulk product ?

I think we make custom attribute column in csv file and use which event that fire when import after check data. and foreach for setting value in custom attribute ?
Please Guide me I want to save custom attribute value in bulk products
Thanks

Best Answer

AFAIK catalog_product_save_before event is not executing on the bulk import process this event is executing only when you save the product from backend.

The correct event would be catalog_product_import_bunch_save_after for the bulk import process

And from your question, you want to set the current admin user Id in current_user_id attribute so I think this is the perfect event for the hook.

So what you need to do create events.xml

<event name="catalog_product_import_bunch_save_after">
        <observer name="some_admin_user" instance="Example\Sample\Observer\AssignAdminId"/>
    </event>

Now you need to create observer AssignAdminId.php

In this observer, you can easily get the imported products and you can update product attributes by using mass action method 'updateAttributes' method

<?php

namespace Example\Sample\Observer;

use Magento\Catalog\Model\Product\Action;
use Magento\Framework\Event\Observer;
use Magento\Framework\Event\ObserverInterface;

class AssignAdminId implements ObserverInterface
{

    private $import;

    /**
     * @var Action
     */
    private $massAction;

    /**
     * AssignAdminId constructor.
     * @param Action $massAction
     */
    public function __construct(
        Action $massAction
    )
    {
        $this->massAction = $massAction;
    }

    public function execute(Observer $observer)
    {
        $this->import = $observer->getEvent()->getAdapter();
        if ($products = $observer->getEvent()->getBunch()) {
            $array_product = [1,2,3,4,5]; //find imported product ID here
            $adminId = 1 ;// find current admin Id here
            $this->massAction->updateAttributes($array_product, array('current_user_id' => $adminId), 0);
        }
    }
}
Related Topic