文档 下载安装 商店 博客 问答 主机

Magento2创建后台网格(Grid)[开发教程]

模块
开发
后端
教程

#1

本教程隶属于Magento2模块开发中文教程系列,翻译自mageplaza.


在本文中,我们将了解如何在Magento 2后台创建管理网格。如您所知,Magento 2 Grid是一种列表,它列出了数据库表中的项目,并提供了一些特性,如:sort、filter、delete、update item等,我将创建helloWorld的产品网格和客户网格。
Magento 2提供了两种创建管理网格的方法:使用布局和使用组件。我们将为他们俩找出细节。在继续之前,请遵循本文的内容,创建一个带有admin菜单的简单模块,我们将使用它来学习网格。在本文中,我将使用示例模块Magentochina_HelloWorld来演示一些演示数据:
##创建网格(Grid)

  • Step 1: 创建数据库模式
  • Step 2: 创建管理菜单
  • Step 3: 创建控制器
  • Step 4: 声明资源
  • Step 5: 使用组件创建管理网格
  • Step 6: 使用布局Layout创建管理网格

Step 1: 创建数据库模式

数据库:我们将使用一个简单的数据库

app/code/Magentochina/HelloWorld/Setup/InstallSchema.php

此文件只在安装模块时执行一次。让我们把这个内容放到这个文件中,创建表:

<?php
namespace Magentochina\HelloWorld\Setup;

class InstallSchema implements \Magento\Framework\Setup\InstallSchemaInterface
{
    /**
     * install tables 创建表
     *
     * @param \Magento\Framework\Setup\SchemaSetupInterface $setup
     * @param \Magento\Framework\Setup\ModuleContextInterface $context
     * @return void
     * @SuppressWarnings(PHPMD.ExcessiveMethodLength)
     */
    public function install(\Magento\Framework\Setup\SchemaSetupInterface $setup, \Magento\Framework\Setup\ModuleContextInterface $context)
    {
        $installer = $setup;
        $installer->startSetup();
        if (!$installer->tableExists('magentochina_helloworld_post')) {  //如果不存在表
            $table = $installer->getConnection()->newTable(
                $installer->getTable('mageplaza_helloworld_post')  //创建表
            )
            ->addColumn(  //增加字段
                'post_id',
                \Magento\Framework\DB\Ddl\Table::TYPE_INTEGER,
                null,
                [
                    'identity' => true,
                    'nullable' => false,
                    'primary'  => true,
                    'unsigned' => true,
                ],
                'Post ID'
            )
            ->addColumn( //增加字段
                'name',
                \Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
                255,
                ['nullable => false'],
                'Post Name'
            )
            ->addColumn( //增加字段
                'url_key',
                \Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
                255,
                [],
                'Post URL Key'
            )
            ->addColumn( //增加字段
                'post_content',
                \Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
                '64k',
                [],
                'Post Post Content'
            )
            ->addColumn( //增加字段
                'tags',
                \Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
                255,
                [],
                'Post Tags'
            )
            ->addColumn( //增加字段
                'status',
                \Magento\Framework\DB\Ddl\Table::TYPE_INTEGER,
                1,
                [],
                'Post Status'
            )
            ->addColumn( //增加字段
                'featured_image',
                \Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
                255,
                [],
                'Post Featured Image'
            )
           
            ->addColumn( //增加字段
                'created_at',
                \Magento\Framework\DB\Ddl\Table::TYPE_TIMESTAMP,
                null,
                [],
                'Post Created At'
            )
            ->addColumn( //增加字段
                'updated_at',
                \Magento\Framework\DB\Ddl\Table::TYPE_TIMESTAMP,
                null,
                [],
                'Post Updated At'
            )
            ->setComment('Post Table');
            $installer->getConnection()->createTable($table); //创建表

            $installer->getConnection()->addIndex( //增加索引
                $installer->getTable('magentochina_helloworld_post'),
                $setup->getIdxName(
                    $installer->getTable('mageplaza_helloworld_post'),
                    ['name','url_key','post_content','tags','featured_image','sample_upload_file'],
                    \Magento\Framework\DB\Adapter\AdapterInterface::INDEX_TYPE_FULLTEXT
                ),
                ['name','url_key','post_content','tags','featured_image','sample_upload_file'],
                \Magento\Framework\DB\Adapter\AdapterInterface::INDEX_TYPE_FULLTEXT
            );
        }
        $installer->endSetup(); //安装完成
    }
}

我们已经做过了:创建Magento 2 CRUD 模型.

##Step 2: 创建管理菜单
管理菜单是指:

详情请查看我们之前的教程Magento2创建后台管理菜单.

Step 3: 创建控制器

创建控制器文件:请阅读创建Magento2控制器文章的细节。
创建名为index.php的控制器文件

app/code/Magentochina/HelloWorld/Controller/Adminhtml/Post/Index.php

内容:

<?php
namespace Magentochina\HelloWorld\Controller\Adminhtml\Post; //命名空间

class Index extends \Magento\Backend\App\Action
{
protected $resultPageFactory = false;
public function __construct( //必须有_construct方法
	\Magento\Backend\App\Action\Context $context,
	\Magento\Framework\View\Result\PageFactory $resultPageFactory
) {
	parent::__construct($context);
	$this->resultPageFactory = $resultPageFactory;
}

public function execute() //必须有execute方法
{
	//调用页面工厂来呈现布局和页面内容
	$this->_setPageData();
    return $this->getResultPage();
}

/*
 * Check permission via ACL resource 检查ACL资源权限
 */
protected function _isAllowed()
{
	return $this->_authorization->isAllowed('Mageplaza_HelloWorld::post_manage');
 }

 public function getResultPage() //获取结果页面
 {
    if (is_null($this->_resultPage)) {
        $this->_resultPage = $this->_resultPageFactory->create();
    }
    return $this->_resultPage;
 }

protected function _setPageData() //设置数据
 {
    $resultPage = $this->getResultPage();
    $resultPage->setActiveMenu('Magentochina_HelloWorld::post'); //添加mune
    $resultPage->getConfig()->getTitle()->prepend((__('Posts'))); //设置title

    //添加面包屑
    $resultPage->addBreadcrumb(__('Magentochina'), __('Magentochina'));
    $resultPage->addBreadcrumb(__('Hello World'), __('Manage Blogs'));

    return $this;
 }
}
## Step 4: 声明资源 在依赖注入文件中声明资源,现在我们将创建di.xml文件,它将连接到模型以获取网格的数据。 文件: >app/code/Magentochina/HelloWorld/etc/di.xml

内容:

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../lib/internal/Magento/Framework/ObjectManager/etc/config.xsd">
    <virtualType name="MagentochinaHelloWorldGirdFilterPool" type="Magento\Framework\View\Element\UiComponent\DataProvider\FilterPool">
        <arguments>
            <argument name="appliers" xsi:type="array">
                <item name="regular" xsi:type="object">Magento\Framework\View\Element\UiComponent\DataProvider\RegularFilter</item>
                <item name="fulltext" xsi:type="object">Magento\Framework\View\Element\UiComponent\DataProvider\FulltextFilter</item>
            </argument>
        </arguments>
    </virtualType>
    <virtualType name="MagentochinaHelloWorldPostGridDataProvider" type="Magento\Framework\View\Element\UiComponent\DataProvider\DataProvider">
        <arguments>
            <argument name="collection" xsi:type="object" shared="false">Magentochina\HelloWorld\Model\ResourceModel\Post\Collection</argument>
            <argument name="filterPool" xsi:type="object" shared="false">MagentochinaHelloWorldGirdFilterPool</argument>
        </arguments>
    </virtualType>
    <type name="Magentochina\HelloWorld\Model\ResourceModel\Post\Grid\Collection">
        <arguments>
            <argument name="mainTable" xsi:type="string">magentochina_helloworld_post</argument>
            <argument name="eventPrefix" xsi:type="string">magentochina_helloworld_post_grid_collection</argument>
            <argument name="eventObject" xsi:type="string">post_grid_collection</argument>
            <argument name="resourceModel" xsi:type="string">Magentochina\HelloWorld\Model\ResourceModel\Post</argument>
        </arguments>
    </type>
    <type name="Magento\Framework\View\Element\UiComponent\DataProvider\CollectionFactory">
        <arguments>
            <argument name="collections" xsi:type="array">
                <item name="magentochina_helloworld_post_listing_data_source" xsi:type="string">Magentochina\HelloWorld\Model\ResourceModel\Post\Grid\Collection</item>
            </argument>
        </arguments>
    </type>
</config>

此文件将声明该表的post集合类、表和资源模型。该源代码将在布局文件中调用,以获取网格的数据。
有两种创建管理网格的方法,在这篇文章的范围内,我们将讨论这两种方法。

Step 5: 使用组件创建管理网格

  • Step 5.1 创建布局文件

我们为动作 helloworld/post/index创建布局文件 helloworld_post_index.xml,文件命名必须符合规范.
文件:

app/code/Magentochina/HelloWorld/view/adminhtml/layout/helloworld_post_index.xml

内容:

<?xml version="1.0"?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../../../lib/internal/Magento/Framework/View/Layout/etc/page_configuration.xsd">
    <update handle="styles"/>
    <body>
        <referenceBlock name="menu">
            <action method="setActive">
                <argument name="itemId" xsi:type="string">Magentochina_HelloWorld::posts</argument>
            </action>
        </referenceBlock>
        <referenceBlock name="page.title">
            <action method="setTitleClass">
                <argument name="class" xsi:type="string">complex</argument>
            </action>
        </referenceBlock>
        <referenceContainer name="content">
            <uiComponent name="magentochina_helloworld_post_listing"/>
        </referenceContainer>
    </body>
</page>

在这个布局文件中,我们声明了这个页面内容的ui组件 <uiComponent name="magentochina_helloworld_post_listing"/>

  • Step 5.2: 创建组件布局文件.

在布局文件中,我们将创建一个组件文件 magentochina_helloworld_post_listing.xml
文件:

app/code/Magentochina/HelloWorld/view/adminhtml/ui_component/magentochina_helloworld_post_listing.xml

内容:

<?xml version="1.0"?>
<listing xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Ui:etc/ui_configuration.xsd">
    <argument name="data" xsi:type="array">
        <item name="js_config" xsi:type="array">
            <item name="provider" xsi:type="string">magentochina_helloworld_post_listing.magentochina_helloworld_post_listing_data_source</item>
            <item name="deps" xsi:type="string">magentochina_helloworld_post_listing.magentochina_helloworld_post_listing_data_source</item>
        </item>
        <item name="spinner" xsi:type="string">magentochina_helloworld_post_columns</item>
        <item name="buttons" xsi:type="array">
            <item name="add" xsi:type="array">
                <item name="name" xsi:type="string">add</item>
                <item name="label" xsi:type="string" translate="true">Add New Post</item>
                <item name="class" xsi:type="string">primary</item>
                <item name="url" xsi:type="string">*/*/new</item>
            </item>
        </item>
    </argument>
    <dataSource name="magentochina_helloworld_post_listing_data_source">
        <argument name="dataProvider" xsi:type="configurableObject">
            <argument name="class" xsi:type="string">MagentochinaHelloWorldPostGridDataProvider</argument>
            <argument name="name" xsi:type="string">magentochina_helloworld_post_listing_data_source</argument>
            <argument name="primaryFieldName" xsi:type="string">post_id</argument>
            <argument name="requestFieldName" xsi:type="string">post_id</argument>
            <argument name="data" xsi:type="array">
                <item name="config" xsi:type="array">
                    <item name="update_url" xsi:type="url" path="mui/index/render"/>
                </item>
            </argument>
        </argument>
        <argument name="data" xsi:type="array">
            <item name="js_config" xsi:type="array">
                <item name="component" xsi:type="string">Magento_Ui/js/grid/provider</item>
            </item>
        </argument>
    </dataSource>
    <container name="listing_top">
        <argument name="data" xsi:type="array">
            <item name="config" xsi:type="array">
                <item name="template" xsi:type="string">ui/grid/toolbar</item>
                <item name="stickyTmpl" xsi:type="string">ui/grid/sticky/toolbar</item>
            </item>
        </argument>
        <bookmark name="bookmarks">
            <argument name="data" xsi:type="array">
                <item name="config" xsi:type="array">
                    <item name="storageConfig" xsi:type="array">
                        <item name="namespace" xsi:type="string">magentochina_helloworld_post_listing</item>
                    </item>
                </item>
            </argument>
        </bookmark>
        <component name="columns_controls">
            <argument name="data" xsi:type="array">
                <item name="config" xsi:type="array">
                    <item name="columnsData" xsi:type="array">
                        <item name="provider" xsi:type="string">magentochina_helloworld_post_listing.magentochina_helloworld_post_listing.magentochina_helloworld_post_columns</item>
                    </item>
                    <item name="component" xsi:type="string">Magento_Ui/js/grid/controls/columns</item>
                    <item name="displayArea" xsi:type="string">dataGridActions</item>
                </item>
            </argument>
        </component>
        <exportButton name="export_button">
            <argument name="data" xsi:type="array">
                <item name="config" xsi:type="array">
                    <item name="selectProvider" xsi:type="string">magentochina_helloworld_post_listing.magentochina_helloworld_post_listing.magentochina_helloworld_post_columns.ids</item>
                </item>
            </argument>
        </exportButton>
        <filterSearch name="fulltext">
            <argument name="data" xsi:type="array">
                <item name="config" xsi:type="array">
                    <item name="provider" xsi:type="string">magentochina_helloworld_post_listing.magentochina_helloworld_post_listing_data_source</item>
                    <item name="chipsProvider" xsi:type="string">magentochina_helloworld_post_listing.magentochina_helloworld_post_listing.listing_top.listing_filters_chips</item>
                    <item name="storageConfig" xsi:type="array">
                        <item name="provider" xsi:type="string">magentochina_helloworld_post_listing.magentochina_helloworld_post_listing.listing_top.bookmarks</item>
                        <item name="namespace" xsi:type="string">current.search</item>
                    </item>
                </item>
            </argument>
        </filterSearch>
        <filters name="listing_filters">
            <argument name="data" xsi:type="array">
                <item name="config" xsi:type="array">
                    <item name="columnsProvider" xsi:type="string">magentochina_helloworld_post_listing.magentochina_helloworld_post_listing.magentochina_helloworld_post_columns</item>
                    <item name="storageConfig" xsi:type="array">
                        <item name="provider" xsi:type="string">magentochina_helloworld_post_listing.magentochina_helloworld_post_listing.listing_top.bookmarks</item>
                        <item name="namespace" xsi:type="string">current.filters</item>
                    </item>
                    <item name="templates" xsi:type="array">
                        <item name="filters" xsi:type="array">
                            <item name="select" xsi:type="array">
                                <item name="component" xsi:type="string">Magento_Ui/js/form/element/ui-select</item>
                                <item name="template" xsi:type="string">ui/grid/filters/elements/ui-select</item>
                            </item>
                        </item>
                    </item>
                    <item name="childDefaults" xsi:type="array">
                        <item name="provider" xsi:type="string">magentochina_helloworld_post_listing.magentochina_helloworld_post_listing.listing_top.listing_filters</item>
                        <item name="imports" xsi:type="array">
                            <item name="visible" xsi:type="string">magentochina_helloworld_post_listing.magentochina_helloworld_post_listing.magentochina_helloworld_post_columns.${ $.index }:visible</item>
                        </item>
                    </item>
                </item>
                <item name="observers" xsi:type="array">
                    <item name="column" xsi:type="string">column</item>
                </item>
            </argument>
        </filters>
        <massaction name="listing_massaction">
            <argument name="data" xsi:type="array">
                <item name="config" xsi:type="array">
                    <item name="selectProvider" xsi:type="string">magentochina_helloworld_post_listing.magentochina_helloworld_post_listing.magentochina_helloworld_post_columns.ids</item>
                    <item name="indexField" xsi:type="string">post_id</item>
                </item>
            </argument>
            <action name="delete">
                <argument name="data" xsi:type="array">
                    <item name="config" xsi:type="array">
                        <item name="type" xsi:type="string">delete</item>
                        <item name="label" xsi:type="string" translate="true">Delete</item>
                        <item name="url" xsi:type="url" path="magentochina_helloworld/post/massDelete"/>
                        <item name="confirm" xsi:type="array">
                            <item name="title" xsi:type="string" translate="true">Delete Posts</item>
                            <item name="message" xsi:type="string" translate="true">Are you sure you wan't to delete selected Posts?</item>
                        </item>
                    </item>
                </argument>
            </action>
            <action name="edit">
                <argument name="data" xsi:type="array">
                    <item name="config" xsi:type="array">
                        <item name="type" xsi:type="string">edit</item>
                        <item name="label" xsi:type="string" translate="true">Edit</item>
                        <item name="callback" xsi:type="array">
                            <item name="provider" xsi:type="string">magentochina_helloworld_post_listing.magentochina_helloworld_post_listing.magentochina_helloworld_post_columns_editor</item>
                            <item name="target" xsi:type="string">editSelected</item>
                        </item>
                    </item>
                </argument>
            </action>
        </massaction>
        <paging name="listing_paging">
            <argument name="data" xsi:type="array">
                <item name="config" xsi:type="array">
                    <item name="storageConfig" xsi:type="array">
                        <item name="provider" xsi:type="string">magentochina_helloworld_post_listing.magentochina_helloworld_post_listing.listing_top.bookmarks</item>
                        <item name="namespace" xsi:type="string">current.paging</item>
                    </item>
                    <item name="selectProvider" xsi:type="string">magentochina_helloworld_post_listing.magentochina_helloworld_post_listing.magentochina_helloworld_post_columns.ids</item>
                </item>
            </argument>
        </paging>
    </container>
    <columns name="magentochina_helloworld_post_columns">
        <argument name="data" xsi:type="array">
            <item name="config" xsi:type="array">
                <item name="storageConfig" xsi:type="array">
                    <item name="provider" xsi:type="string">magentochina_helloworld_post_listing.magentochina_helloworld_post_listing.listing_top.bookmarks</item>
                    <item name="namespace" xsi:type="string">current</item>
                </item>
                <item name="editorConfig" xsi:type="array">
                    <item name="selectProvider" xsi:type="string">magentochina_helloworld_post_listing.magentochina_helloworld_post_listing.magentochina_helloworld_post_columns.ids</item>
                    <item name="enabled" xsi:type="boolean">true</item>
                    <item name="indexField" xsi:type="string">post_id</item>
                    <item name="clientConfig" xsi:type="array">
                        <item name="saveUrl" xsi:type="url" path="magentochina_helloworld/post/inlineEdit"/>
                        <item name="validateBeforeSave" xsi:type="boolean">false</item>
                    </item>
                </item>
                <item name="childDefaults" xsi:type="array">
                    <item name="fieldAction" xsi:type="array">
                        <item name="provider" xsi:type="string">magentochina_helloworld_post_listing.magentochina_helloworld_post_listing.magentochina_helloworld_post_columns_editor</item>
                        <item name="target" xsi:type="string">startEdit</item>
                        <item name="params" xsi:type="array">
                            <item name="0" xsi:type="string">${ $.$data.rowIndex }</item>
                            <item name="1" xsi:type="boolean">true</item>
                        </item>
                    </item>
                    <item name="storageConfig" xsi:type="array">
                        <item name="provider" xsi:type="string">magentochina_helloworld_post_listing.magentochina_helloworld_post_listing.listing_top.bookmarks</item>
                        <item name="root" xsi:type="string">columns.${ $.index }</item>
                        <item name="namespace" xsi:type="string">current.${ $.storageConfig.root}</item>
                    </item>
                </item>
            </item>
        </argument>
        <selectionsColumn name="ids">
            <argument name="data" xsi:type="array">
                <item name="config" xsi:type="array">
                    <item name="resizeEnabled" xsi:type="boolean">false</item>
                    <item name="resizeDefaultWidth" xsi:type="string">55</item>
                    <item name="indexField" xsi:type="string">post_id</item>
                </item>
            </argument>
        </selectionsColumn>
        <column name="post_id">
            <argument name="data" xsi:type="array">
                <item name="config" xsi:type="array">
                    <item name="filter" xsi:type="string">textRange</item>
                    <item name="sorting" xsi:type="string">asc</item>
                    <item name="label" xsi:type="string" translate="true">ID</item>
                </item>
            </argument>
        </column>
        <column name="name">
            <argument name="data" xsi:type="array">
                <item name="config" xsi:type="array">
                    <item name="filter" xsi:type="string">text</item>
                    <item name="editor" xsi:type="array">
                        <item name="editorType" xsi:type="string">text</item>
                        <item name="validation" xsi:type="array">
                            <item name="required-entry" xsi:type="boolean">true</item>
                        </item>
                    </item>
                    <item name="label" xsi:type="string" translate="true">Name</item>
                </item>
            </argument>
        </column>
        <column name="url_key">
            <argument name="data" xsi:type="array">
                <item name="config" xsi:type="array">
                    <item name="filter" xsi:type="string">text</item>
                    <item name="visible" xsi:type="boolean">false</item>
                    <item name="label" xsi:type="string" translate="true">URL Key</item>
                    <item name="dataType" xsi:type="string">text</item>
                </item>
            </argument>
        </column>
        <column name="tags">
            <argument name="data" xsi:type="array">
                <item name="config" xsi:type="array">
                    <item name="filter" xsi:type="string">text</item>
                    <item name="visible" xsi:type="boolean">false</item>
                    <item name="label" xsi:type="string" translate="true">Tags</item>
                    <item name="dataType" xsi:type="string">text</item>
                </item>
            </argument>
        </column>
        <column name="status">
            <argument name="data" xsi:type="array">
                <item name="options" xsi:type="object">Magento\Config\Model\Config\Source\Yesno</item>
                <item name="config" xsi:type="array">
                    <item name="filter" xsi:type="string">select</item>
                    <item name="label" xsi:type="string" translate="true">Status</item>
                    <item name="component" xsi:type="string">Magento_Ui/js/grid/columns/select</item>
                    <item name="dataType" xsi:type="string">select</item>
                </item>
            </argument>
        </column>
        <column name="sample_country_selection">
            <argument name="data" xsi:type="array">
                <item name="options" xsi:type="object">Magento\Config\Model\Config\Source\Locale\Country</item>
                <item name="config" xsi:type="array">
                    <item name="filter" xsi:type="string">select</item>
                    <item name="visible" xsi:type="boolean">false</item>
                    <item name="label" xsi:type="string" translate="true">Sample Country Selection</item>
                    <item name="component" xsi:type="string">Magento_Ui/js/grid/columns/select</item>
                    <item name="dataType" xsi:type="string">select</item>
                </item>
            </argument>
        </column>
        <column name="created_at" class="Magento\Ui\Component\Listing\Columns\Date">
            <argument name="data" xsi:type="array">
                <item name="config" xsi:type="array">
                    <item name="filter" xsi:type="string">dateRange</item>
                    <item name="component" xsi:type="string">Magento_Ui/js/grid/columns/date</item>
                    <item name="dataType" xsi:type="string">date</item>
                    <item name="label" xsi:type="string" translate="true">Created</item>
                </item>
            </argument>
        </column>
        <column name="updated_at" class="Magento\Ui\Component\Listing\Columns\Date">
            <argument name="data" xsi:type="array">
                <item name="config" xsi:type="array">
                    <item name="filter" xsi:type="string">dateRange</item>
                    <item name="component" xsi:type="string">Magento_Ui/js/grid/columns/date</item>
                    <item name="dataType" xsi:type="string">date</item>
                    <item name="label" xsi:type="string" translate="true">Modified</item>
                </item>
            </argument>
        </column>
        <actionsColumn name="actions" class="Magentochina\HelloWorld\Ui\Component\Listing\Column\PostActions">
            <argument name="data" xsi:type="array">
                <item name="config" xsi:type="array">
                    <item name="resizeEnabled" xsi:type="boolean">false</item>
                    <item name="resizeDefaultWidth" xsi:type="string">107</item>
                    <item name="indexField" xsi:type="string">post_id</item>
                </item>
            </argument>
        </actionsColumn>
    </columns>
    <container name="sticky">
        <argument name="data" xsi:type="array">
            <item name="config" xsi:type="array">
                <item name="component" xsi:type="string">Magento_Ui/js/grid/sticky/sticky</item>
                <item name="toolbarProvider" 
xsi:type="string">magentochina_helloworld_post_listing.magentochina_helloworld_post_listing.listing_top</item>
                <item name="listingProvider" xsi:type="string">magentochina_helloworld_post_listing.magentochina_helloworld_post_listing.magentochina_helloworld_post_columns</item>
            </item>
        </argument>
    </container>
</listing>

使用此代码,您将知道如何声明网格布局(按钮,列),调用数据源。请刷新缓存,并访问这个网格页面,管理员网格将显示如下:

  • Step 5.3: 创建容器
    正如文章开头说的,Magento 2网格将支持一些与网格交互的操作:sort,filter,action delete/ update等等,排序特性是网格的默认动作。您可以单击列标题来对项目进行排序。我们将了解如何为我们的网格构建其特性。
    为此,我们将在组件布局文件的父列表中创建一个容器元素:
    文件:

app/code/Magentochina/HelloWorld/view/adminhtml/ui_component/magentochina_helloworld_post_listing.xml

内容:

    <?xml version="1.0" encoding="UTF-8"?>
    <listing xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Ui:etc/ui_configuration.xsd">
    <!-- ... other block of code -->
    <container name="listing_top">
        <argument name="data" xsi:type="array">
            <item name="config" xsi:type="array">
                <item name="template" xsi:type="string">ui/grid/toolbar</item>
                <item name="stickyTmpl" xsi:type="string">ui/grid/sticky/toolbar</item>
            </item>
        </argument>
    </container>
    <!-- ... other block of code -->
    </listing>
  • Step 5.4: 创建书签
    这个参数用于定义模板 Magento/Ui/view/base/web/templates/grid/toolbar.html将被载入,以定义knockout js来处理此网格中的所有ajax更新操作。我们将在这个容器的内部定义上面的特性。您可以在列元素之前或之后放置这个容器元素来定义工具栏的位置(在列之上或下面)。让我们来看看每个动作的细节:书签(Bookmark)
    文件:

app/code/Mageplaza/HelloWorld/view/adminhtml/ui_component/mageplaza_helloworld_post_listing.xml

内容:

<?xml version="1.0" encoding="UTF-8"?>
<listing xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Ui:etc/ui_configuration.xsd">
    <!-- ... other block of code -->
    <container name="listing_top">
        <bookmark name="bookmarks">
            <argument name="data" xsi:type="array">
                <item name="config" xsi:type="array">
                    <item name="storageConfig" xsi:type="array">
                        <item name="namespace" xsi:type="string">magentochina_helloworld_post_listing</item>
                    </item>
                </item>
            </argument>
        </bookmark>
    </container>
    <!-- ... other block of code -->
</listing>

这将添加书签功能,允许管理设置不同的网格状态。每个状态可能有一个不同的列列表。因此,对于每个管理员用户,他们可以选择显示与他相关的信息。

  • Step 5.5: 列控制(Column controls)
    此节点将添加一个列列表框,允许管理员用户可以选择在网格上显示哪些列。在更改了这个列表之后,admin可以将这个状态保存为一个书签,以便快速访问这个状态。
    文件:

app/code/Magentochina/HelloWorld/view/adminhtml/ui_component/magentochina_helloworld_post_listing.xml

内容:

<?xml version="1.0" encoding="UTF-8"?>
<listing xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Ui:etc/ui_configuration.xsd">
    <!-- ... other block of code -->
    <component name="columns_controls">
        <argument name="data" xsi:type="array">
            <item name="config" xsi:type="array">
                <item name="columnsData" xsi:type="array">
                    <item name="provider" xsi:type="string">magentochina_helloworld_post_listing.magentochina_helloworld_post_listing.magentochina_helloworld_post_columns</item>
                </item>
                <item name="component" xsi:type="string">Magento_Ui/js/grid/controls/columns</item>
                <item name="displayArea" xsi:type="string">dataGridActions</item>
            </item>
        </argument>
    </component>
    <!-- ... other block of code -->
</listing>
  • Step 5.6: 全文搜索 Full text search
    该节点将在网格顶部添加一个搜索框。您可以使用它来搜索表中的所有数据。
    文件:

app/code/Magentochina/HelloWorld/view/adminhtml/ui_component/magentochina_helloworld_post_listing.xml

<?xml version="1.0" encoding="UTF-8"?>
<listing xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Ui:etc/ui_configuration.xsd">
    <!-- ... other block of code -->
    <filterSearch name="fulltext">
            <argument name="data" xsi:type="array">
                <item name="config" xsi:type="array">
                    <item name="provider" xsi:type="string">magentochina_helloworld_post_listing.magentochina_helloworld_post_listing_data_source</item>
                    <item name="chipsProvider" xsi:type="string">magentochina_helloworld_post_listing.magentochina_helloworld_post_listing.listing_top.listing_filters_chips</item>
                    <item name="storageConfig" xsi:type="array">
                        <item name="provider" xsi:type="string">magentochina_helloworld_post_listing.magentochina_helloworld_post_listing.listing_top.bookmarks</item>
                        <item name="namespace" xsi:type="string">current.search</item>
                    </item>
                </item>
            </argument>
        </filterSearch>
    <!-- ... other block of code -->
</listing>
  • Step 5.7: 过滤 Filter
    该节点为每一列定义过滤器框。您可以通过点击网格顶部的Filter按钮来看到这一点。
    文件:

app/code/Magentochina/HelloWorld/view/adminhtml/ui_component/magentochina_helloworld_post_listing.xml

<?xml version="1.0" encoding="UTF-8"?>
<listing xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Ui:etc/ui_configuration.xsd">
    <!-- ... other block of code -->
    <filters name="listing_filters">
            <argument name="data" xsi:type="array">
                <item name="config" xsi:type="array">
                    <item name="columnsProvider" xsi:type="string">magentochina_helloworld_post_listing.magentochina_helloworld_post_listing.magentochina_helloworld_post_columns</item>
                    <item name="storageConfig" xsi:type="array">
                        <item name="provider" xsi:type="string">magentochina_helloworld_post_listing.magentochina_helloworld_post_listing.listing_top.bookmarks</item>
                        <item name="namespace" xsi:type="string">current.filters</item>
                    </item>
                    <item name="templates" xsi:type="array">
                        <item name="filters" xsi:type="array">
                            <item name="select" xsi:type="array">
                                <item name="component" xsi:type="string">Magento_Ui/js/form/element/ui-select</item>
                                <item name="template" xsi:type="string">ui/grid/filters/elements/ui-select</item>
                            </item>
                        </item>
                    </item>
                    <item name="childDefaults" xsi:type="array">
                        <item name="provider" xsi:type="string">magentochina_helloworld_post_listing.magentochina_helloworld_post_listing.listing_top.listing_filters</item>
                        <item name="imports" xsi:type="array">
                            <item name="visible" xsi:type="string">magentochina_helloworld_post_listing.magentochina_helloworld_post_listing.magentochina_helloworld_post_columns.${ $.index }:visible</item>
                        </item>
                    </item>
                </item>
                <item name="observers" xsi:type="array">
                    <item name="column" xsi:type="string">column</item>
                </item>
            </argument>
        </filters>
    <!-- ... other block of code -->
</listing>
  • Step 5.8: 大动作 Mass actions
    此节点将向网格中添加大众操作选择。管理员可以使用这个动作在多个项目上快速采取一些动作。
    文件:

app/code/Magentochina/HelloWorld/view/adminhtml/ui_component/magentochina_helloworld_post_listing.xml

<?xml version="1.0" encoding="UTF-8"?>
<listing xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Ui:etc/ui_configuration.xsd">
    <!-- ... other block of code -->
    <massaction name="listing_massaction">
            <argument name="data" xsi:type="array">
                <item name="config" xsi:type="array">
                    <item name="selectProvider" xsi:type="string">magentochina_helloworld_post_listing.magentochina_helloworld_post_listing.magentochina_helloworld_post_columns.ids</item>
                    <item name="indexField" xsi:type="string">post_id</item>
                </item>
            </argument>
            <action name="delete">
                <argument name="data" xsi:type="array">
                    <item name="config" xsi:type="array">
                        <item name="type" xsi:type="string">delete</item>
                        <item name="label" xsi:type="string" translate="true">Delete</item>
                        <item name="url" xsi:type="url" path="magentochina_helloworld/post/massDelete"/>
                        <item name="confirm" xsi:type="array">
                            <item name="title" xsi:type="string" translate="true">Delete Posts</item>
                            <item name="message" xsi:type="string" translate="true">Are you sure you wan't to delete selected Posts?</item>
                        </item>
                    </item>
                </argument>
            </action>
            <action name="edit">
                <argument name="data" xsi:type="array">
                    <item name="config" xsi:type="array">
                        <item name="type" xsi:type="string">edit</item>
                        <item name="label" xsi:type="string" translate="true">Edit</item>
                        <item name="callback" xsi:type="array">
                            <item name="provider" xsi:type="string">magentochina_helloworld_post_listing.magentochina_helloworld_post_listing.magentochina_helloworld_post_columns_editor</item>
                            <item name="target" xsi:type="string">editSelected</item>
                        </item>
                    </item>
                </argument>
            </action>
        </massaction>
    <!-- ... other block of code -->
</listing>
  • Step 5.9: 分页 Paging
    此节点将为网格添加分页。如果在表中有大量的数据,这是很有用的。
    文件:

app/code/Magentochina/HelloWorld/view/adminhtml/ui_component/magentochina_helloworld_post_listing.xml

<?xml version="1.0" encoding="UTF-8"?>
<listing xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Ui:etc/ui_configuration.xsd">
    <!-- ... other block of code -->
    <paging name="listing_paging">
        <argument name="data" xsi:type="array">
            <item name="config" xsi:type="array">
                <item name="storageConfig" xsi:type="array">
                    <item name="provider" xsi:type="string">magentochina_helloworld_post_listing.magentochina_helloworld_post_listing.listing_top.bookmarks</item>
                    <item name="namespace" xsi:type="string">current.paging</item>
                </item>
                <item name="selectProvider" xsi:type="string">magentochina_helloworld_post_listing.magentochina_helloworld_post_listing.magentochina_helloworld_post_columns.ids</item>
            </item>
        </argument>
    </paging>
    <!-- ... other block of code -->
</listing>
  • Step 5.10: 导出按钮 Export button
    此节点将添加一个导出按钮,您可以导出网格的数据。
<?xml version="1.0" encoding="UTF-8"?>
<listing xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Ui:etc/ui_configuration.xsd">
    <!-- ... other block of code -->
    <exportButton name="export_button">
        <argument name="data" xsi:type="array">
            <item name="config" xsi:type="array">
                <item name="selectProvider" xsi:type="string">magentochina_helloworld_post_listing.magentochina_helloworld_post_listing.magentochina_helloworld_post_columns.ids</item>
            </item>
        </argument>
    </exportButton>
    <!-- ... other block of code -->
</listing>

尝试清除缓存之后,返回后台刷新页面,你将会看到:

Step 6: 使用布局Layout创建管理网格

**注意!**如果您已经完成了步骤5,就跳过这一步.因为组件和Layout选其一即可.
我们刚刚学习了如何使用组件添加Magento 2网格。现在,我们将看到如何使用正常的布局/块(layout/block)文件来完成它。

Step 6.1: 创建网格块 Create block for this grid

文件:

app/code/Magentochina/Mageplaza/Block/Adminhtml/Post.php

<?php
namespace Magentochina\HelloWorld\Block\Adminhtml;
class Post extends \Magento\Backend\Block\Widget\Grid\Container
{
    /**
     * constructor
     *
     * @return void
     */
    protected function _construct() //构造方法
    {
        $this->_controller = 'adminhtml_post'; //控制器
        $this->_blockGroup = 'magentochina_HelloWorld'; //模块名
        $this->_headerText = __('Posts'); //title
        $this->_addButtonLabel = __('Create New Post'); //按钮
        parent::_construct();
    }
}

网格块(Grid block)将扩展 \Magento\Backend\Block\Widget\Grid\Container,并在 **_construct()**方法中定义一些变量。

  • _blockGroup 为模块名,固定格式是VendorName_ModuleName
  • _controller 是块(Block)文件夹内的网格块(Grid Block)路径。在这个helloWorld中,我设置了网格。在Adminhtml/Blog文件夹内的php文件
  • _headerText 为网格页面的Title
  • _addButtonLabel 是添加新按钮的标签。

###Step 6.2: 创建布局文件 Create layout file
现在我们需要一个布局文件来连接网格块并呈现网格。让我们创建这个文件:

app/code/Magentochina/Magentochina/view/adminhtml/layout/helloworld_post_index.xml

<?xml version="1.0"?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
    <update handle="styles"/>
    <body>
        <referenceContainer name="content">
            <!--<uiComponent name="magentochina_post_grid"/>-->
            <block class="Magentochina\HelloWorld\Block\Adminhtml\Post" name="magentochina_post_grid">
                <block class="Magento\Backend\Block\Widget\Grid" name="magentochina_post_grid.grid" as="grid">
                    <arguments>
                        <argument name="id" xsi:type="string">post_id</argument>
                        <argument name="dataSource" xsi:type="object">Magentochina\HelloWorld\Model\ResourceModel\Blog\Collection</argument>
                        <argument name="default_sort" xsi:type="string">id</argument>
                        <argument name="default_dir" xsi:type="string">ASC</argument>
                        <argument name="save_parameters_in_session" xsi:type="string">1</argument>
                    </arguments>
                    <block class="Magento\Backend\Block\Widget\Grid\ColumnSet" name="magentochina_post_grid.grid.columnSet" as="grid.columnSet">
                        <arguments>
                            <argument name="rowUrl" xsi:type="array">
                                <item name="path" xsi:type="string">*/*/edit</item>
                            </argument>
                        </arguments>
                        <block class="Magento\Backend\Block\Widget\Grid\Column" as="id">
                            <arguments>
                                <argument name="header" xsi:type="string" translate="true">ID</argument>
                                <argument name="index" xsi:type="string">post_id</argument>
                                <argument name="type" xsi:type="string">text</argument>
                                <argument name="column_css_class" xsi:type="string">col-id</argument>
                                <argument name="header_css_class" xsi:type="string">col-id</argument>
                            </arguments>
                        </block>
                        <block class="Magento\Backend\Block\Widget\Grid\Column" as="title">
                            <arguments>
                                <argument name="header" xsi:type="string" translate="true">Title</argument>
                                <argument name="index" xsi:type="string">title</argument>
                                <argument name="type" xsi:type="string">text</argument>
                                <argument name="column_css_class" xsi:type="string">col-id</argument>
                                <argument name="header_css_class" xsi:type="string">col-id</argument>
                            </arguments>
                        </block>
                        <block class="Magento\Backend\Block\Widget\Grid\Column" as="creation_time">
                            <arguments>
                                <argument name="header" xsi:type="string" translate="true">Created Time</argument>
                                <argument name="index" xsi:type="string">creation_time</argument>
                                <argument name="type" xsi:type="string">date</argument>
                                <argument name="column_css_class" xsi:type="string">col-id</argument>
                                <argument name="header_css_class" xsi:type="string">col-id</argument>
                            </arguments>
                        </block>
                    </block>
                </block>
            </block>
        </referenceContainer>
    </body>
</page>

在这个布局文件中,我们将为网格定义一些参数。主要的参数是数据源。这个参数将链接到我们在di中声明的数据源。上面的xml文件连接到数据库并获取此网格的数据。
###Step 6.4: 添加列 Add Column
列集将定义在网格中显示的列。如果您想使用massAction,您可以将此块添加到网格元素:

<block class="Magento\Backend\Block\Widget\Grid\Massaction" name="magentochina.helloWorld.massaction" as="grid.massaction">
    <arguments>
        <argument name="massaction_id_field" xsi:type="string">post_id</argument>
        <argument name="form_field_name" xsi:type="string">ids</argument>
        <argument name="use_select_all" xsi:type="string">1</argument>
        <argument name="options" xsi:type="array">
            <item name="disable" xsi:type="array">
                <item name="label" xsi:type="string" translate="true">Delete</item>
                <item name="url" xsi:type="string">*/*/massDelete</item>
            </item>
        </argument>
    </arguments>
</block>

在此之后,请刷新缓存,然后到grid页面查看结果。它应该这样显示:

####本教程翻译自mageplaza,如果你想查看完整的教程,请点击这里.译者:西帅
####如果觉得本站翻译得内容对您有帮助,又没有时间帮助翻译回馈社区.请打赏我们,您的支持是我们的动力:

####转载说明:非常欢迎转载,但是必须保证文章的完整性并附上原文地址和翻译原文的地址,保证阅读者不会产生歧义.

Magento2模块开发中文教程索引