Back to Top

Delete operation in Magento 2

Updated 1 August 2024

Let’s give our blog writer an option for deleting his/her blog. After this, we will have completed the CRUD operations.

Just like before we need to edit the view/frontend/templates/list.phtml

Updated code for view/frontend/templates/list.phtml file

<table>
    <tr>
        <th>
            <?= __("Id")?>
        </th>
        <th>
            <?= __("Title")?>
        </th>
        <th>
            <?= __("Content")?>
        </th>
        <th>
            <?= __("Edit")?>
        </th>
        <th>
            <?= __("Delete")?>
        </th>
    </tr>
    <?php
    $blogs = $block->getBlogs();

    foreach ($blogs as $blog) {?>
    <tr>
        <td>
            <?= $escaper->escapeHtml($blog->getId())?>
        </td>
        <td>
            <?= $escaper->escapeHtml($blog->getTitle())?>
        </td>
        <td>
            <?= substr($escaper->escapeHtml($blog->getContent()), 0, 20).'...'?>
        </td>
        <td>
            <a href="<?= $escaper->escapeUrl($block->getUrl('blog/manage/edit', ['id'=>$escaper->escapeHtml($blog->getId())]))?>">
                <?= __('Edit') ?>
            </a>
        </td>
        <td>
            <a href="<?= $escaper->escapeUrl($block->getUrl('blog/manage/delete', ['id'=>$escaper->escapeHtml($blog->getId())]))?>"
                onclick="return confirm('Are you sure you want to delete this blog?');">
                <?= __('Delete') ?>
            </a>
        </td>
    </tr>
    <?php } ?>
</table>

Here we have added another column “Delete” and in the delete link we have used javascript’s confirm dialog.

2021-02-16_20-46

We will redirect the user to the list page after deleting the blog. So we just need to create the controller file. Please check the readymade Magento 2 Blog Extension

Searching for an experienced
Magento 2 Company ?
Find out More

Let’s create Controller/Manage/Delete.php file,

Code for Controller/Manage/Delete.php file

<?php
namespace Webkul\BlogManager\Controller\Manage;

use Magento\Customer\Controller\AbstractAccount;
use Magento\Framework\App\Action\Context;
use Magento\Customer\Model\Session;

class Delete extends AbstractAccount
{
    /**
     * @var \Webkul\BlogManager\Model\BlogFactory
     */
    protected $blogFactory;

    /**
     * @var Magento\Customer\Model\Session
     */
    protected $customerSession;

    /**
     * @var \Magento\Framework\Message\ManagerInterface
     */
    protected $messageManager;

    /**
     * Dependency Initilization
     *
     * @param Context $context
     * @param \Webkul\BlogManager\Model\BlogFactory $blogFactory
     * @param Session $customerSession
     * @param \Magento\Framework\Message\ManagerInterface $messageManager
     */
    public function __construct(
        Context $context,
        \Webkul\BlogManager\Model\BlogFactory $blogFactory,
        Session $customerSession,
        \Magento\Framework\Message\ManagerInterface $messageManager
    ) {
        $this->blogFactory = $blogFactory;
        $this->customerSession = $customerSession;
        $this->messageManager = $messageManager;
        parent::__construct($context);
    }

    /**
     * Provides content
     *
     * @return Magento\Framework\Controller\Result\Redirect
     */
    public function execute()
    {
        $blogId = $this->getRequest()->getParam('id');
        $customerId = $this->customerSession->getCustomerId();
        $isAuthorised = $this->blogFactory->create()
                                    ->getCollection()
                                    ->addFieldToFilter('user_id', $customerId)
                                    ->addFieldToFilter('entity_id', $blogId)
                                    ->getSize();
        if (!$isAuthorised) {
            $this->messageManager->addError(__('You are not authorised to delete this blog.'));
            return $this->resultRedirectFactory->create()->setPath('blog/manage');
        } else {
            $model = $this->blogFactory->create()->load($blogId);
            $model->delete();
            $this->messageManager->addSuccess(__('You have successfully deleted the blog.'));
        }     
        return $this->resultRedirectFactory->create()->setPath('blog/manage');
    }
}

There is nothing much to talk about here because we have seen very similar codes before also. The only thing you have to notice is the $model->delete() method. After loading the model we have deleted it with the delete() method and we have redirected to the list page.

2021-02-16_20-47

The folder structure till now,

Selection_114
Folder Structure

Next Blog -> Magento 2 Development 14: CSS and JS

Previous Blog -> Magento 2 Development 12: Editing and Updating

. . .

Leave a Comment

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


Be the first to comment.

Back to Top

Message Sent!

If you have more details or questions, you can reply to the received confirmation email.

Back to Home