I have a M2 extension that provides me to a frontend dashboard to allow suppliers to upload products. The extension also provides a product list table that show supplier products. Is there a way to approve or delete a product from frontend instead of login into backend as admin user? I mean put some buttons into the product list table and assign the respective functionality to the button. Is there a way to do that?
1 Answer
We can use \Magento\Catalog\Api\ProductRepositoryInterface
to delete the product.
However, the most important thing is that we need to check the product belongs to the current customer or not. You should create your own logic for this class.
app/code/Vendor/Module/Controller/Product/Delete.php
class Delete extends \Magento\Framework\App\Action\Action
{
protected $productRepository;
protected $productLoader;
public function __construct(
\Magento\Catalog\Api\ProductRepositoryInterface $productRepository,
\Vendor\Module\Controller\AbstractController\ProductLoader $productLoader,
Context $context
)
{
$this->productRepository = $productRepository;
$this->productLoader = $productLoader;
parent::__construct($context);
}
public function execute()
{
$productId = $this->_request->getParam('product_id');
$product = $this->productRepository->getById(productId);
/** @var \Magento\Framework\Controller\Result\Redirect $resultRedirect */
$resultRedirect = $this->resultRedirectFactory->create();
if($this->productLoader->canView($product)) {
try {
$this->productRepository->delete($product);
} catch (\Magento\Framework\Exception\LocalizedException $e) {
$this->messageManager->addError($e->getMessage());
return $resultRedirect->setPath('*/*/*');
}
} else {
......
}
return $resultRedirect->setPath('*/*/*');
}
}
We need to check the product can be deleted by the current customer app/code/Vendor/Module/Controller/AbstractController/ProductLoader.php
class ProductLoader {
/**
* @var \Magento\Customer\Model\Session
*/
protected $customerSession;
public function __construct(
\Magento\Customer\Model\Session $customerSession,
......
) {
$this->customerSession = $customerSession;
}
public function canView(\Magento\Catalog\Api\Data\ProductInterface $product)
{
$customerId = $this->customerSession->getCustomerId();
//Check if this product belongs to the current customer, return true or false
}
}
We can follow the logic of Sales module: vendor/magento/module-sales/Controller/AbstractController
.
-
could you please check this magento.stackexchange.com/questions/315691/… Jun 23, 2020 at 7:57