Magento 2: Delete data in custom module
-
10-10-2020 - |
Question
I need to delete my custom table data, I tried below code, but its not works for me.
my table:
test_id product_id testing
1 15 12345
my code:
try{
$model = $this->zipcodeFactory->create();
$modelcollection = $this->zipcodeFactory->create()->getCollection();
foreach($modelcollection as $modeldata){
$model->load($modeldata['test_id']);
$model->delete();
}
}catch (Exception $e){
}
Suggest Me What i Miss in this code.
Solution
Use \Magento\Ui\Component\MassAction\Filter
class for massDelete
protected $zipcodeFactory;
public function __construct(
\Magento\Ui\Component\MassAction\Filter $filter,
\Vendor\Module\Model\ResourceModel\Class\zipcodeFactory $zipcodeFactory,
\Magento\Backend\App\Action\Context $context
) {
$this->filter = $filter;
$this->zipcodeFactory = $zipcodeFactory;
parent::__construct($context);
}
public function execute()
{
try {
$logCollection = $this->filter->getCollection($this->zipcodeFactory->create());
foreach ($logCollection as $item) {
$item->delete();
}
echo "Items Deleted"; exit;
} catch (\Exception $e) {
$this->messageManager->addError($e->getMessage());
}
}
OTHER TIPS
If you want avoid do a foreach, you can use a collection walk.
$modelcollection->walk('delete');
Licensed under: CC-BY-SA with attribution
Not affiliated with magento.stackexchange