Magento 2: MassAction Model LSD method delete()
-
30-12-2020 - |
Question
My massaction functionalities are working fine. According to CodingStandard it shows this warning.
----------------------------------------------------------------------
38 | WARNING | Model LSD method delete() detected in loop
----------------------------------------------------------------------
I have attached my MassDelete code below.
<?php
namespace modulename\Wallet\Controller\Adminhtml\Transaction;
use Magento\Framework\Controller\ResultFactory;
use Magento\Backend\App\Action\Context;
use Magento\Ui\Component\MassAction\Filter;
use modulename\Wallet\Model\ResourceModel\Transaction\CollectionFactory;
class MassDelete extends \Magento\Backend\App\Action
{
public function __construct(
Context $context,
Filter $filter,
CollectionFactory $collectionFactory
) {
$this->_filter = $filter;
$this->_collectionFactory = $collectionFactory;
parent::__construct($context);
}
public function execute()
{
$data = $this->getRequest()->getParams();
$collection = $this->_collectionFactory->create();
$collection->addFieldToFilter('transaction_id', ['in' => $data]);
$recordDeleted = 0;
foreach ($collection->getItems() as $auctionProduct) {
$auctionProduct->setId($auctionProduct->getId());
$auctionProduct->delete();
$recordDeleted++;
}
$this->messageManager->addSuccess(
__('A total of %1 record(s) have been deleted.', $recordDeleted)
);
return $this->resultFactory->create(ResultFactory::TYPE_REDIRECT)->setPath('*/*/index');
}
}
Solution
LSD comes from load/save/delete
. You should not call these methods inside loops.
But in this case, if you want to hide the dirt under the rug you can crete a new method in your class
private function deleteItem($item)
{
$item->delete();
}
and replace the line $auctionProduct->delete();
with
$this->deleteItem($auctionProduct);
and the code sniffer will stop complaining.
OTHER TIPS
If hiding the LSD delete method behind the private
visibility domain doesn't impress PHPCS you may try calling your method inside an array_walk
loop instead of foreach. From what I know array_walk
is less performant than foreach
.
- You're using the delete() method inside a loop which in not recommended and has to be avoided.
Licensed under: CC-BY-SA with attribution
Not affiliated with magento.stackexchange