Hướng dẫn lập trình module Magento 2: Tạo view

Trong bài 4 của loạt bài hướng dẫn lập trình module Magento 2, chúng ta sẽ cùng nhau xem cách hoạt động của view.

Như các bạn đã biết, ở bài 1 chúng ta tạo 1 module đơn giản hiển thị dòng chữ Hello World ra trang store, để làm được điều đó chúng ta đã sử dụng view. Nên có thể hiểu 1 cách đơn giản rằng view giúp chúng ta hiển thị nội dung trên trang.

View trong Magento 2 được xây dựng từ Block, Layout và Template.

Chúng ta đã tạo bảng và thêm dữ liệu trong 2 bài viết trước, bây giờ chúng ta sẽ sử dụng view để hiển thị những dữ liệu đó trên trang store.

Bước 1: Tạo Controller.

Các bạn tạo Magetop/Helloworld/Controller/Learning/View.php với đoạn code:

<?php
namespace Magetop\Helloworld\Controller\Learning;

use Magento\Framework\App\Action\Action;
use Magento\Framework\View\Result\PageFactory;
use Magento\Framework\App\Action\Context;

class View extends Action
{
    protected $pageFactory;

    public function __construct(Context $context, PageFactory $pageFactory)
    {
        parent::__construct($context);
        $this->pageFactory = $pageFactory;
    }

    public function execute()
    {
        $resultPage = $this->pageFactory->create();
        // Tạo tiêu đề
        $resultPage->getConfig()->getTitle()->set(__('Danh sách bài viết'));

        // Tạo breadcrumb
        /** @var \Magento\Theme\Block\Html\Breadcrumbs */
        if($resultPage->getLayout()->getBlock('breadcrumbs')) {
            $breadcrumbs = $resultPage->getLayout()->getBlock('breadcrumbs');
            $breadcrumbs->addCrumb('TrangChu',
                [
                    'label' => __('Home'),
                    'title' => __('TrangChu'),
                    'link' => $this->_url->getUrl('')
                ]
            );
            $breadcrumbs->addCrumb('Blog',
                [
                    'label' => __('Posts'),
                    'title' => __('BaiViet')
                ]
            );
        }
        return $resultPage;
    }
}

Bước 2: Tạo Block.

Tạo Magetop/Helloworld/Block/Bloglist.php với đoạn code:

<?php
namespace Magetop\Helloworld\Block;

use Magento\Framework\View\Element\Template;
use Magetop\Helloworld\Model\ResourceModel\Posts\CollectionFactory;

class Bloglist extends Template
{
    protected $PostsFactory;

    public function __construct(Template\Context $context, CollectionFactory $postsFactory)
    {
        $this->PostsFactory = $postsFactory;
        parent::__construct($context);
    }

    public function GetBlog(){
        $blog = $this->PostsFactory->create();
        return $blog;
    }
}

Bước 3: Tạo view.

B3.1: Trước tiên tạo file css Magetop/Helloworld/view/frontend/web/css/styleTable.css bên trong có đoạn code:

table, th, td {
    border: 1px solid black;
    border-collapse: collapse;
}

B3.2: Tạo layout Magetop/Helloworld/view/frontend/layout/hello_learning_view.xml, tên của file xml phải dựa theo quy tắc routes_controller_action. Trong file hello_learning_view.xml có đoạn code sau:

<?xml version="1.0" encoding="UTF-8"?>
<!--
/**
 * hello_learning_view
 *
 * @copyright Copyright © 2020 MAGETOP. All rights reserved.
 * @author    [email protected]
 */
-->
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" layout="1column" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
    <head>
        <css src="Magetop_Helloworld::css/styleTable.css"/>
    </head>
    <body>
        <referenceContainer name="content">
            <block class="Magetop\Helloworld\Block\Bloglist" name="hello_learning_view" template="Magetop_Helloworld::blogs.phtml"/>
        </referenceContainer>
    </body>
</page>

B3.3: Tạo template, các bạn chú ý để file ở định dạng phtml Magetop/Helloworld/view/frontend/templates/blogs.phtml với đoạn code:

<?php
    $posts = $block->GetBlog();
?>

<table>
  <tr>
        <th class="blog-id">Id</th>
        <th class="blog-name">Tiêu Đề</th>
        <th>Summary</th>
        <th>Nội Dung</th>
  </tr>
    <?php
        foreach ($posts as $data){
            echo '<tr>
                    <td>'.$data->getId().'</td>
                    <td>'.$data->getTitle().'</td>
                    <td>'.$data->getSummary().'</td>
                    <td>'.$data->getDescription().'</td>
                  </tr>';
        }
    ?>
</table>

Sau khi tạo hết xong các bạn nhớ lưu lại và chạy 2 lệnh:

  • php bin/magento setup:upgrade
  • php bin/magento setup:static-content:deploy -f 

Chạy xong truy cập theo địa chỉ ten-mien.com/hello/learning/view để kiểm tra.

Sử dụng view hiển thị database lên trang store Magento 2

Dữ liệu hiển thị trên trang đúng với dữ liệu chúng ta đã thêm vào.

Vậy là mình đã hướng dẫn xong cách sử dụng view để hiển thị database lên trang store Magento 2.

Để dễ hiểu hơn các bạn nên đọc các bài viết trước của mình: Hướng dẫn lập trình module Magento 2 (phần 3).

Ở bài viết tiếp theo mình sẽ hướng dẫn các bạn cách tạo menu admin cho module trong Magento 2.

Cảm ơn các bạn đã đọc bài viết.

5 4 votes
Article Rating

Callula Huy

Callula is the Marketing Executive at Magetop. With more than 5 years of copywriting under her belt, Callula is into creating valuable content that is straight to the point. Life student. Workaholic. Foreign languages and traveling aficionado.

Leave a Reply or put your Question here

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x