Ask your Question

PEOPLE YOU MIGHT KNOW

Deepak
Deepak

Cluster Credit Manager

Patna,  India
Maheshkumar
Maheshkumar

Fresher software Devloper

Gandhinagar,  India
Vaibhav
Vaibhav

Web Developer & Software Developer

Ichalkarnji,  India
Vinod
Vinod

Team Lead in User Admin Team

PUNE,  India
Awadh
Awadh

SAP MM Consultant

Airoli,  India

Write to us

Ask Question

How to delete a product in Magento2 Programatically

Aditya Singh
How to delete a product in Magento2 Programatically

 To delete a product from frontend 

1. On delete icon/link we need to pass the product ID which we need to delete.
2. We need to create a  controller class to execute the delete process and
  need to write the delete code under execute method of class.
 
 class Deleteproduct extends MagentoFrameworkAppActionAction
{   
    protected $_productRepositoryInterface;
    
public function __construct(
          MagentoFrameworkAppActionContext $context,
          MagentoCatalogModelProductRepository $productRepository,
          MagentoFrameworkRegistry $registry)
        
       {
        parent::__construct($context);
        $this->productRepository = $productRepository;
        $this->registry = $registry;
    
        }
 
     public function execute()
   
       {
    $productInfo = $this->getRequest()->getParams();
    $productID  = $productInfo[\'id\'];
    $this->registry->register(\'isSecureArea\', true);
    $product = $this->productRepository->getById($productID);
            $this->productRepository->delete($product);
    $this->messageManager->addSuccess(  __(\'Product has been deleted!\') );
                      
        }
}

Aditya Singh

Please rotate your device

We don't support landscape mode on your device. Please rotate to portrait mode for the best view of our site