Magento 2 Training : Unit 5 – Lesson C

The 2 last controllers to create are :
– delete
– massDelete

Let’s go !

Delete controller creation

Create the file :
app/code/Maxime/Jobs/Controller/Adminhtml/Department/Delete.php

Put this code inside :

<?php
namespace Maxime\Jobs\Controller\Adminhtml\Department;

use Magento\Backend\App\Action;

class Delete extends Action
{
    protected $_model;

    /**
     * @param Action\Context $context
     * @param \Maxime\Jobs\Model\Department $model
     */
    public function __construct(
        Action\Context $context,
        \Maxime\Jobs\Model\Department $model
    ) {
        parent::__construct($context);
        $this->_model = $model;
    }

    /**
     * {@inheritdoc}
     */
    protected function _isAllowed()
    {
        return $this->_authorization->isAllowed('Maxime_Jobs::department_delete');
    }

    /**
     * Delete action
     *
     * @return \Magento\Framework\Controller\ResultInterface
     */
    public function execute()
    {
        $id = $this->getRequest()->getParam('id');
        /** @var \Magento\Backend\Model\View\Result\Redirect $resultRedirect */
        $resultRedirect = $this->resultRedirectFactory->create();
        if ($id) {
            try {
                $model = $this->_model;
                $model->load($id);
                $model->delete();
                $this->messageManager->addSuccess(__('Department deleted'));
                return $resultRedirect->setPath('*/*/');
            } catch (\Exception $e) {
                $this->messageManager->addError($e->getMessage());
                return $resultRedirect->setPath('*/*/edit', ['id' => $id]);
            }
        }
        $this->messageManager->addError(__('Department does not exist'));
        return $resultRedirect->setPath('*/*/');
    }
}

Construct and isAllowed are here, and you well know its.
On the execute, we check we have an ID, we load the model, and we delete it !
We redirect the user with a success or error message.

MassDelete controller creation

To delete many elements in a row, you jave to check them and choose the “Delete” option :

massaction

So we have to create a controller to do that :
app/code/Maxime/Jobs/Controller/Adminhtml/Department/MassDelete.php

And the code is :

<?php
namespace Maxime\Jobs\Controller\Adminhtml\Department;

use Magento\Framework\Controller\ResultFactory;
use Magento\Backend\App\Action\Context;
use Magento\Ui\Component\MassAction\Filter;
use Maxime\Jobs\Model\ResourceModel\Department\CollectionFactory;

class MassDelete extends \Magento\Backend\App\Action
{
    /**
     * @var Filter
     */
    protected $filter;

    /**
     * @var CollectionFactory
     */
    protected $collectionFactory;


    /**
     * @param Context $context
     * @param Filter $filter
     * @param CollectionFactory $collectionFactory
     */
    public function __construct(Context $context, Filter $filter, CollectionFactory $collectionFactory)
    {
        $this->filter = $filter;
        $this->collectionFactory = $collectionFactory;
        parent::__construct($context);
    }
    /**
     * Execute action
     *
     * @return \Magento\Backend\Model\View\Result\Redirect
     * @throws \Magento\Framework\Exception\LocalizedException|\Exception
     */
    public function execute()
    {
        $collection = $this->filter->getCollection($this->collectionFactory->create());
        $collectionSize = $collection->getSize();
        foreach ($collection as $item) {
            $item->delete();
        }

        $this->messageManager->addSuccess(__('A total of %1 record(s) have been deleted.', $collectionSize));

        /** @var \Magento\Backend\Model\View\Result\Redirect $resultRedirect */
        $resultRedirect = $this->resultFactory->create(ResultFactory::TYPE_REDIRECT);
        return $resultRedirect->setPath('*/*/');
    }
}

We declare a new object CollectionFactory, so create the file :
app/code/Maxime/Jobs/Model/ResourceModel/Department/CollectionFactory.php

Put this code :

<?php
namespace Maxime\Jobs\Model\ResourceModel\Department;

class CollectionFactory
{
    /**
     * Object Manager instance
     *
     * @var \Magento\Framework\ObjectManagerInterface
     */
    protected $_objectManager = null;

    /**
     * Instance name to create
     *
     * @var string
     */
    protected $_instanceName = null;

    /**
     * Factory constructor
     *
     * @param \Magento\Framework\ObjectManagerInterface $objectManager
     * @param string $instanceName
     */
    public function __construct(\Magento\Framework\ObjectManagerInterface $objectManager, $instanceName = '\\Maxime\\Jobs\\Model\\ResourceModel\\Department\\Collection')
    {
        $this->_objectManager = $objectManager;
        $this->_instanceName = $instanceName;
    }

    /**
     * Create class instance with specified parameters
     *
     * @param array $data
     * @return \Maxime\Jobs\Model\ResourceModel\Department\Collection
     */
    public function create(array $data = array())
    {
        return $this->_objectManager->create($this->_instanceName, $data);
    }
}

The important thing is the variable instanceName which define our collection.

Before testing, check the file app/code/Maxime/Jobs/Model/ResourceModel/Department/Collection.php and verify you have a line like :
protected $_idFieldName = \Maxime\Jobs\Model\Department::DEPARTMENT_ID;

If not, you must add it. Now you can mass delete some elements !

deleted

Next step is practical exercises which repeats the 2 last units, but for the “Job” element.

Continue training
Return to previous lesson
Delete and massActions on Magento 2 admin
Tagged on:     

9 thoughts on “Delete and massActions on Magento 2 admin

  • 07/06/2016 at 14:28
    Permalink

    Hello Maxime Huran,

    Really awesome tutorial for admin side. I am trying to perform massdelete but it give me error like following
    Invalid method Magento\Framework\View\Element\UiComponent\DataProvider\Document::delete(Array())

    In mass delete action i am getting the collection but while deleting the item it give me above error.

    Reply
      • 11/30/2016 at 11:04
        Permalink

        Check the di.xml
        virtual type has to have Grid\ before Collection

        And item the same inside the the argument

        …….\Grid\Collection

        Reply
        • 05/10/2017 at 04:18
          Permalink

          I have change
          “Training\ComputerGame\Model\ResourceModel\ComputerGame\Collection” to “Training\ComputerGame\Model\ResourceModel\ComputerGame\Grid\Collection”
          but the system show error in grid list.
          Class Training\ComputerGame\Model\ResourceModel\ComputerGame\Grid\Collection does not exist

          Reply
    • 03/15/2018 at 08:01
      Permalink

      Try the following code MassDelete.php
      public function execute()
      {
      $collection = $this->_filter->getCollection($this->_collectionFactory->create());
      $collectionSize = $collection->getSize();
      $recordDeleted=0;
      foreach ($collection as $item) {
      $deleteItem = $this->_objectManager->get(‘Milople\Warehouse\Model\Grid’)->load($item->getRowId());
      $deleteItem->delete();
      $recordDeleted++;
      }
      $this->messageManager->addSuccess(__(‘A total of %1 record(s) have been deleted.’ ,$recordDeleted));
      return $this->resultFactory->create(ResultFactory::TYPE_REDIRECT)->setPath(‘*/*/’);
      }

      In the above code provide the path where your row id has been present.
      It worked for me.

      Reply
  • 07/09/2017 at 13:38
    Permalink

    Try this at console

    sudo chmod -R 777 pub/ var/ && bin/magento cache:clean && bin/magento setup:upgrade && bin/magento setup:di:compile

    Reply
  • 10/23/2017 at 09:14
    Permalink

    Good tutorial admin Mangento 2. You are awasome!

    Reply
  • 05/25/2018 at 16:36
    Permalink

    Excelent tutorial!, Thanks

    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *

We use cookies to ensure that we give you the best experience on our website.
Ok