Magento 2 Development 10: Deleting

0

 

Let’s give our blog writer an option to delete 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

<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>
<?= $blog->getId()?>
</td>
<td>
<?= $blog->getTitle()?>
</td>
<td>
<?= substr($blog->getContent(), 0, 20).'...'?>
</td>
<td>
<a href="<?= $block->getUrl('blog/manage/edit', ['id'=>$blog->getId()])?>">
<?= __('Edit') ?>
</a>
</td>
<td>
<a href="<?= $block->getUrl('blog/manage/delete', ['id'=>$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



Let’s create 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
{
public $blogFactory;
public $customerSession;
public $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);
}
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. Only thing you have to notice is $model->delete() method. After loading the model we have deleted it with delete() and we have redirected to the list page.

2021-02-16_20-47

The folder structure till now,

2021-02-16_20-49


Post a Comment

0Comments
Post a Comment (0)
To Top