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.

2
  • Let me know if you have any issue. Jul 19, 2017 at 18:00
  • Thanks @PrincePatel , my custom module issue, now fixed 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());
    }
}
2
  • 1
    I like your ans :) Jul 19, 2017 at 17:34
  • Is it possible to addFieldToFilter by product_id and record delete without foreach ? @PrincePatel Jan 19, 2018 at 5:50
2

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

$modelcollection->walk('delete');

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.