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.

  • Let me know if you have any issue. – Prince Patel Jul 19 '17 at 18:00
  • Thanks @PrincePatel , my custom module issue, now fixed – Rajkumar .E Jul 19 '17 at 19:37
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());
    }
}
  • 1
    I like your ans :) – Rama Chandran M Jul 19 '17 at 17:34
  • Is it possible to addFieldToFilter by product_id and record delete without foreach ? @PrincePatel – Rohan Hapani Jan 19 '18 at 5:50
0

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, privacy policy and cookie policy

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