1

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.

Prince Patel
23.1k10 gold badges102 silver badges124 bronze badges
asked Jul 19, 2017 at 15:05
2
  • Let me know if you have any issue. Commented Jul 19, 2017 at 18:00
  • Thanks @PrincePatel , my custom module issue, now fixed Commented Jul 19, 2017 at 19:37

2 Answers 2

2

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());
 }
}
answered Jul 19, 2017 at 16:37
2
  • 1
    I like your ans :) Commented Jul 19, 2017 at 17:34
  • Is it possible to addFieldToFilter by product_id and record delete without foreach ? @PrincePatel Commented Jan 19, 2018 at 5:50
2

If you want avoid do a foreach, you can use a collection walk.

$modelcollection->walk('delete');
answered Jan 31, 2019 at 13:33

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.