I have created an admin user and i only want to display those products that is uploaded by him in backend but here all the products is displaying which other users have added instead of his products.
Please suggest a solution.
I have created an admin user and i only want to display those products that is uploaded by him in backend but here all the products is displaying which other users have added instead of his products.
Please suggest a solution.
I think its too long to explain all things in answer, but I can give you starting point so you can start from something,
Create a new product attribute with admin_user_id
in assigned to all your product attribute set and perform reindex
.
Create a new observer
for the catalog_product_save_before
event. You can find the similar answer here Get product object after save
Note: above link answer is for catalog_product_save_after
but you can easily change the event with catalog_product_save_before
On save event you need to find current admin user id,which you can easily find from admin session. here is the answer How to get admin user detail ?
After getting the admin user id save id to product attribute which we have created in first step. like
$product->setData('admin_user_id',1)
// this is example, you can replace with dynamic
So on every product save you can find the admin user id, which is useful to differentiate the product between admin user.
So after saving the product now its turn to hide the product for current user, which you can easily do by writing the after
plugin
for the Magento\Catalog\Ui\DataProvider\Product\ProductDataProvider
In this class Magento
prepare the product
collection
for product
grid. In this class you can find getData
method. so this is your location filter the products with current admin user id.
To create a plugin File: app/code/YOURVENDOR/YOURMODULE/etc/di.xml
<type name="Magento\Catalog\Ui\DataProvider\Product\ProductDataProvider">
<plugin name="YOUR_PLUGIN_NAME" type="YOURVENDOR\YOURMODULENAME\Plugin\ProductDataProvider" />
</type>
Here is the location,
public function aftergetData(\Magento\Catalog\Ui\DataProvider\Product\ProductDataProvider $subject
)
{
if (!$subject->getCollection()->isLoaded()) {
$subject->getCollection()->addFieldToFilter('admin_user_id','1'); //replace with dynamic admin user from session
$subject->getCollection()->load();
}
.......................
}
that's it to filter the product collection based on admin user.
<?php namespace Learning\HelloPage\Observer; use Magento\Framework\Event\ObserverInterface; class Productsavebefore implements ObserverInterface { protected $authSession; public function execute(\Magento\Framework\Event\Observer $observer, \Magento\Backend\Model\Auth\Session $authSession) { $this->authSession = $authSession; $current_admin_id = $this->authSession->getUser()->getId(); $_product = $observer->getProduct(); $_product->setData('admin_user_id', $current_admin_id); $_product->save(); } }
Commented
Sep 4, 2017 at 12:12