Magento2 Deleting

让我们为博客作者提供一个删除他/她的博客的选项。 此后,我们将完成CRUD操作。就像之前我们需要编辑 view/frontend/templates/list.phtml一样。

<table>
    <tr>
        <th>
            <?= __("Id")?>
        </th>
        <th>
            <?= __("Title")?>
        </th>
        <th>
            <?= __("Content")?>
        </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>

在这里,我们添加了另一列“删除”,在删除链接中,我们使用了javascript的“确认”对话框。

删除博客后,我们会将用户重定向到列表页面。 因此,我们只需要创建控制器文件。

让我们创建Controller / Manage / Delete.php文件

<?php

namespace Yshuq\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,
        \Yshuq\BlogManager\Model\BlogFactory $blogFactory,
        \Magento\Framework\Message\ManagerInterface $messageManager
    ) {
        $this->messageManager = $messageManager;
        parent::__construct($context);
    }

    public function  execute()
    {
        // TODO: Implement execute() method.
        $blogId = $this->getRequest()->getParam('id');
        $customerId =  $this->customerSession->getCustomerId();
        $isAuthorised = $this->blogFactory->create()
             ->getCollection()
             ->addFieldToFilter('user_id',$customerId)
             ->addFieldToFilter('entity_id',$blogId)
             ->getszie();
        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');
        }
    }
}

这里没有什么要讨论的,因为我们之前也看过非常相似的代码。 您唯一需要注意的是$ model-> delete()方法。 加载模型后,我们已使用delete()将其删除,并已重定向到列表页面。

写完代码然后执行下面命令:

php -d memory_limit=-1 bin/magento setup:di:compile

操作blog列表执行删除操作。

到现在为止的文件夹结构,