1

I'm very new to Magento, i created a Mass Action for Delete i write this code in /EC/Downloads/view/adminhtml/ui_component/ec_downloads_items.xml

<?xml version="1.0"?>
<listing xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Ui:etc/ui_configuration.xsd">
    <listingToolbar name="listing_top">
        <settings>
            <sticky>true</sticky>
        </settings>
        <paging name="listing_paging"/>
        <filters name="listing_filters"/>

        <massaction name="listing_massaction">
            <action name="delete">
                <settings>
                    <confirm>
                        <message translate="true">Delete selected items?</message>
                        <title translate="true">Delete items</title>
                    </confirm>
                    <url path="*/items/MassDelete"/>
                    <type>delete</type>
                    <label translate="true">Delete</label>
                </settings>
            </action>
        </massaction>
    </listingToolbar>

    <columns name="ec_downloads_items_columns">
        <selectionsColumn name="ids">
            <argument name="data" xsi:type="array">
                <item name="config" xsi:type="array">
                    <item name="resizeEnabled" xsi:type="boolean">false</item>
                    <item name="resizeDefaultWidth" xsi:type="string">55</item>
                    <item name="indexField" xsi:type="string">downloads_id</item>
                    <item name="sortOrder" xsi:type="number">10</item>
                </item>
            </argument>
        </selectionsColumn>

        <column name="downloads_id">.......</column>

    </columns>
</listing>

and this code in /EC/Downloads/Controller/Adminhtml/Items/MassDelete.php

<?php
namespace EC\Downloads\Controller\Adminhtml\Items;

use Magento\Backend\App\Action;

/**
 * Class MassDelete
 */
class MassDelete extends \Magento\Backend\App\Action
{
    /**
     * @return \Magento\Backend\Model\View\Result\Redirect
     */
    public function execute()
    {
        $ids = $this->getRequest()->getParam('downloads_id');
        echo $ids;
        exit;

        if (!is_array($ids) || empty($ids)) {
            echo 'Bad';
            exit; 

            $this->messageManager->addError(__('Please select Item.'));
        } else {
            echo 'Good';
            exit; 

            try {
                foreach ($ids as $id) {
                    $emp = $this->_objectManager->get('EC\Downloads\Model\Downloads')->load($id);
                    $emp->delete();
                }
                $this->messageManager->addSuccess(
                    __('A total of %1 record(s) have been deleted.', count($ids))
                );
            } catch (\Exception $e) {
                $this->messageManager->addError($e->getMessage());
            }
        }
        return $this->resultRedirectFactory->create()->setPath('downloads/index/items');
    }
}

code in /EC/Downloads/Model/ResourceModel/Items.php

<?php

namespace EC\Downloads\Model\ResourceModel;
/**
 * Class Items
 * @package EC\Downloads\Model\ResourceModel
 */
class Items extends \Magento\Framework\Model\ResourceModel\Db\AbstractDb
{
    /**
     *
     */
    protected function _construct()
    {
        $this->_init('downloads', 'downloads_id');
    }
}

When i try to delete more items it's not working, when i try to echo|exit, i found that i dosen't go to the delete part coz ids is empty.

  • Can you please add more code of ui_component xml file? – Kazim Noorani May 21 at 12:22
  • @KazimNoorani Updated.... – Partab Saifuddin Zakir May 21 at 12:27
  • Please check my answer. Might help you. – Kazim Noorani May 21 at 12:32
  • Is it helpful ? – Kazim Noorani May 21 at 12:38
  • I can't see the <item> tag name provider and <dataSource> tag process and make the UI component work with this data. – Shekhar Suman May 22 at 9:33
0

It's working fine. Try this

UI component Form

    <action name="delete">
        <argument name="data" xsi:type="array">
            <item name="config" xsi:type="array">
                <item name="type" xsi:type="string">delete</item>
                <item name="label" xsi:type="string" translate="true">Delete</item>

                <item name="url" xsi:type="url" path="router_name/index/massdelete"/>
                <item name="confirm" xsi:type="array">
                    <item name="title" xsi:type="string" translate="true">Delete</item>
                    <item name="message" xsi:type="string" translate="true">Do you want to delete selected row record?</item>
                </item>
            </item>
        </argument>
    </action>

Controller

<?php
namespace EC\Downloads\Controller\Adminhtml\Index;
use Magento\Framework\Controller\ResultFactory;
use Magento\Backend\App\Action\Context;
use Magento\Ui\Component\MassAction\Filter;
use EC\Downloads\Model\ResourceModel\Post\CollectionFactory;

class MassDelete extends \Magento\Backend\App\Action
{

    protected $_filter;
    protected $serviceFactory;

    public function __construct(
        Context $context,
        Filter $filter,
        \EC\Downloads\Model\DownloadsFactory $serviceFactory,
        CollectionFactory $collectionFactory
    ) {

        $this->_filter = $filter;
        $this->collectionFactory = $collectionFactory;
        $this->serviceFactory = $serviceFactory;
        parent::__construct($context);
    }

    public function execute()
    {
        $collection = $this->_filter->getCollection($this->collectionFactory->create());
        $collectionSize = $collection->getSize();
        foreach ($collection as $item) 
        {
        $item = $this->serviceFactory->create()->load($item->getDownloadsId());
        $item->delete();
        }

        $this->messageManager->addSuccess(__('A total of %1 element(s) have been deleted.', $collectionSize));
        /** @var \Magento\Backend\Model\View\Result\Redirect $resultRedirect */
        $resultRedirect = $this->resultFactory->create(ResultFactory::TYPE_REDIRECT);
        return $resultRedirect->setPath('downloads/index/items');
    }   
}

Note: CODE TESTED

  • Getting this error: Exception #0 (Zend_Db_Statement_Exception): SQLSTATE[42S22]: Column not found: 1054 Unknown column '' in 'where clause', query was: SELECT COUNT(*) FROM downloads AS main_table WHERE (`` IN('7')) Exception #1 (PDOException): SQLSTATE[42S22]: Column not found: 1054 Unknown column '' in 'where clause' @ARUNPRABAKARANM – Partab Saifuddin Zakir May 22 at 11:11
  • Yeah I need to add this line in Model\ResourceModel\Module\Collection.php ... protected $_idFieldName = 'downloads_id'; – Partab Saifuddin Zakir May 22 at 11:27
  • Did you get an error till now? – Arunprabakaran M May 22 at 14:02
  • Yes bro...! no doubt .... :) – Partab Saifuddin Zakir May 24 at 9:51
  • Bro @ARUNPRABAKARANM please help me out magento.stackexchange.com/questions/276387/… – Partab Saifuddin Zakir May 28 at 13:51
0

Does your resourceModel collection have a key defined?


namespace Xigen\Data\Model\ResourceModel\Fitment;

class Collection extends \Magento\Framework\Model\ResourceModel\Db\Collection\AbstractCollection
{

    /**
     * @var string
     */
    protected $_idFieldName = 'fitment_id';

    /**
     * Define resource model
     *
     * @return void
     */
    protected function _construct()
    {
        $this->_init(
            \Xigen\Data\Model\Fitment::class,
            \Xigen\Data\Model\ResourceModel\Fitment::class
        );
    }
}

Just for reference here is my MassDelete.php


namespace Xigen\Data\Controller\Adminhtml\Fitment;

/**
 * Mass-Delete Controller.
 */
class MassDelete extends \Magento\Backend\App\Action
{

    const ADMIN_RESOURCE = 'Xigen_Data::import';

    private $filter;
    private $collectionFactory;

    /**
     * MassDelete constructor.
     *
     * @param \Magento\Backend\App\Action\Context $context
     * @param \Magento\Ui\Component\MassAction\Filter $filter
     * @param \Xigen\Data\Model\ResourceModel\Import\CollectionFactory $collectionFactory
     */
    public function __construct(
        \Magento\Backend\App\Action\Context $context,
        \Magento\Ui\Component\MassAction\Filter $filter,
        \Xigen\Data\Model\ResourceModel\Fitment\CollectionFactory $collectionFactory,
        \Xigen\Data\Model\FitmentFactory $fitmentFactory
    ) {
        $this->filter = $filter;
        $this->fitmentFactory = $fitmentFactory;
        parent::__construct($context);
    }
    /**
     * Execute action.
     *
     * @return \Magento\Backend\Model\View\Result\Redirect
     * @throws \Magento\Framework\Exception\LocalizedException|\Exception
     */
    public function execute()
    {
        $ids = $this->getRequest()->getPost('selected');
        if ($ids) {
            $collection = $this->fitmentFactory->create()
                ->getCollection()
                ->addFieldToFilter('fitment_id', array('in' => $ids));

            $collectionSize = $collection->getSize();

            $deletedItems = 0;
            foreach ($collection as $item) {
                try {
                    $item->delete();
                    $deletedItems++;
                } catch (\Exception $e) {
                    $this->messageManager->addErrorMessage($e->getMessage());
                }
            }
            if ($deletedItems != 0) {
                if ($collectionSize != $deletedItems) {
                    $this->messageManager->addErrorMessage(
                        __('Failed to delete %1 fitment item(s).', $collectionSize - $deletedItems)
                    );
                }
                $this->messageManager->addSuccessMessage(
                    __('A total of %1 fitment item(s) have been deleted.', $deletedItems)
                );
            }
        }
        /** @var \Magento\Backend\Model\View\Result\Redirect $resultRedirect */
        $resultRedirect = $this->resultFactory->create(\Magento\Framework\Controller\ResultFactory::TYPE_REDIRECT);
        return $resultRedirect->setPath('*/*/');
    }
}
0

Just for reference, this is my code of ui_component listing xml file.

<listingToolbar name="listing_top">
        <argument name="data" xsi:type="array">
            <item name="config" xsi:type="array">
                <item name="sticky" xsi:type="boolean">true</item>
            </item>
        </argument>
        <bookmark name="bookmarks"/>
        <columnsControls name="columns_controls"/>
        <filters name="listing_filters"/>
        <massaction name="listing_massaction">
            <argument name="data" xsi:type="array">
                <item name="config" xsi:type="array">
                    <item name="component" xsi:type="string">Magento_Ui/js/grid/tree-massactions</item>
                </item>
            </argument>
            <action name="delete">
                <argument name="data" xsi:type="array">
                    <item name="config" xsi:type="array">
                        <item name="type" xsi:type="string">delete</item>
                        <item name="label" xsi:type="string" translate="true">Delete</item>
                        <item name="url" xsi:type="url" path="bannerslider/banner/massDelete"/>
                        <item name="confirm" xsi:type="array">
                            <item name="title" xsi:type="string" translate="true">Delete Slider</item>
                            <item name="message" xsi:type="string" translate="true">Are you sure you wan't to delete selected Banners?</item>
                        </item>
                    </item>
                </argument>
            </action>                
        </massaction>
        <paging name="listing_paging"/>
    </listingToolbar>

And this is massDelete Controller.

<?php
namespace A\BannerSlider\Controller\Adminhtml\Banner;

use Magento\Backend\App\Action;
use Magento\Backend\App\Action\Context;
use Magento\Ui\Component\MassAction\Filter;
use A\BannerSlider\Model\ResourceModel\Banner\CollectionFactory;

class MassDelete extends Action
{
    protected $filter;

    protected $collectionFactory;

    public function __construct(
        Filter $filter,
        CollectionFactory $collectionFactory,
        Context $context
    ) {
        $this->filter            = $filter;
        $this->collectionFactory = $collectionFactory;

        parent::__construct($context);
    }

    public function execute()
    {
        $collection = $this->filter->getCollection($this->collectionFactory->create());

        $delete = 0;
        foreach ($collection as $item) {
            $item->delete();
            $delete++;
        }
        $this->messageManager->addSuccess(__('A total of %1 record(s) have been deleted.', $delete));
        $resultRedirect = $this->resultFactory->create(\Magento\Framework\Controller\ResultFactory::TYPE_REDIRECT);

        return $resultRedirect->setPath('*/*/');
    }
}
0

Paste your MassDelete.php with below one:

                    <?php
                    namespace EC\Downloads\Controller\Adminhtml\Items;

                    use Magento\Backend\App\Action;

                    /**
                     * Class MassDelete
                     */
                    class MassDelete extends \Magento\Backend\App\Action
                    {
                        /**
                         * @return \Magento\Backend\Model\View\Result\Redirect
                         */

                        public function __construct(
                            \Magento\Backend\App\Action\Context $context,
                            \Magento\Ui\Component\MassAction\Filter $filter,
                            \EC\Downloads\Model\ResourceModel\Items\CollectionFactory $collectionFactory,
                            \EC\Downloads\Model\ItemFactory $itemFactory
                        ) {
                            $this->filter = $filter;
                            $this->itemFactory = $itemFactory;
                            parent::__construct($context);
                        }  

                          public function execute()
                        {
                            $ids = $this->getRequest()->getPost();
                            if ($ids) {
                                $collection = $this->itemFactory->create()
                                    ->getCollection()
                                    ->addFieldToFilter('downloads_id', array('in' => $ids));

                                $collectionSize = $collection->getSize();

                                $deletedItems = 0;
                                foreach ($collection as $item) {
                                    try {
                                        $item->delete();
                                        $deletedItems++;
                                    } catch (\Exception $e) {
                                        $this->messageManager->addErrorMessage($e->getMessage());
                                    }
                                }
                                if ($deletedItems != 0) {
                                    if ($collectionSize != $deletedItems) {
                                        $this->messageManager->addErrorMessage(
                                            __('Failed to delete %1 fitment item(s).', $collectionSize - $deletedItems)
                                        );
                                    }
                                    $this->messageManager->addSuccessMessage(
                                        __('A total of %1 fitment item(s) have been deleted.', $deletedItems)
                                    );
                                }
                            }
                            /** @var \Magento\Backend\Model\View\Result\Redirect $resultRedirect */
                            $resultRedirect = $this->resultFactory->create(\Magento\Framework\Controller\ResultFactory::TYPE_REDIRECT);
                            return $resultRedirect->setPath('downloads/index/items');
                        }
                    }
  • not working.... – Partab Saifuddin Zakir May 21 at 12:55
  • ->addFieldToFilter('downloads_id', array('in' => $ids)); getting error in this line... – Partab Saifuddin Zakir May 21 at 12:55
  • Exception #0 (Exception): Warning: PDO::quote() expects parameter 1 to be string, object given in /var/www/html/mg.local/vendor/magento/zendframework1/library/Zend/Db/Adapter/Pdo/Abstract.php on line 296 – Partab Saifuddin Zakir May 21 at 12:56
  • Are you getting $ids? – Rutvee Sojitra May 21 at 13:00
  • yes... like this: id => 1 and 3: Zend\Stdlib\Parameters Object ( [storage:ArrayObject:private] => Array ( [selected] => Array ( [0] => 1 [1] => 3 ) [filters] => Array ( [placeholder] => true ) [namespace] => ec_downloads_items [form_key] => TfQNKpKNTlflHLwE ) ) – Partab Saifuddin Zakir May 21 at 13:07

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.