0

I created a new admin_user role, this role has access to the products page and can add a new product.

So, I want to save the ID of the current admin_user to know who's added the product.

The first method I think about is to add a new foreign key to catalog_product_website table on DB with the ID of admin_user table.

And after that, I will use an event to save the ID on this table, on save the product.

But with some search, I found there's EAV method.

So, it's better to use the first method? Or it's better to use EAV and create attribute not visibly and save on it the ID of the current user?

1

You can achieve by creating a new product attribute. let say admin_user_id. now you need to feel this value on product saving from backend by using Magento events. If you are not familiar with Magento events and observer please read this from the Magento DevDocs.

In your case, you should use catalog_product_save_before event. this event is executing before saving the product. In this event, you will get a product object so you can use this object and set the current admin user Id(you can get it from current admin session). For example,

Create events.xml under etc/adminhtml/events.xml

    <event name="catalog_product_save_before">
        <observer name="assign_admin_user_id_on_save" instance="Example\Sample\Observer\AssignAdminIdOnSave"/>
    </event>   

Now you need to create an observer class which should implement Magento\Framework\Event\ObserverInterface

<?php

namespace Example\Sample\Observer;

use Magento\Framework\Event\Observer;
use Magento\Framework\Event\ObserverInterface;
use Magento\Backend\Model\Auth\Session as adminSession;

class AssignAdminIdOnSave implements ObserverInterface
{
    /**
     * @var adminSession
     */
    private $adminSession;

    /**
     * AssignAdminIdOnSave constructor.
     * @param adminSession $adminSession
     */
    public function __construct(
        adminSession $adminSession
    )
    {
        $this->adminSession = $adminSession;
    }

    public function execute(Observer $observer)
    {
        $product = $observer->getProduct();
        $adminId=$this->adminSession->getUser()->getId();
        $product->setAdminUserId($adminId) ;
    }
}

Please note that this will work only when you are creating/saving the product from the backend.

If you also want admin user Id on product import then you need to create another observer for catalog_product_save_before. I already wrote the answer for this so you can check from this link

  • Thanks for your reply sir, I create the admin_user_id attribute using EAV, and I write the observer, where I can check if the ID is inserted or not? – sayou Apr 26 at 14:55

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.