如何将订单网格集合连接到Magento2中的自定义表?


Answers:


12

Magento 2将自定义列添加到销售订单网格,

加入

Magento \ Sales \ Order \ Grid \ Collection

对于任何表,使用插件将是最好的选择,因为这不依赖于重写并使代码精简。

在模块的etc / di.xml中创建插件

<type name="Magento\Framework\View\Element\UiComponent\DataProvider\CollectionFactory">
    <plugin name="sales_order_additional_columns" type="Vendor\ModuleName\Plugins\AddColumnsSalesOrderGridCollection" sortOrder="100" disabled="false" />
</type>

因此,我们正在拦截

Magento \ Framework \ View \ Element \ UiComponent \ DataProvider \ CollectionFactory

因为如果你看看

Magento \ Sales \ etc \ di.xml

你会看到

Magento \ Sales \ Order \ Grid \ Collection

被注入

Magento \ Framework \ View \ Element \ UiComponent \ DataProvider \ CollectionFactory

在模块中创建一个Plugin文件夹和一个插件类

<?php namespace Vendor\ModuleName\Plugins;

use Magento\Framework\Message\ManagerInterface as MessageManager;
use Magento\Sales\Model\ResourceModel\Order\Grid\Collection as SalesOrderGridCollection;

class AddColumnsSalesOrderGridCollection
{
    private $messageManager;
    private $collection;

    public function __construct(MessageManager $messageManager,
        SalesOrderGridCollection $collection
    ) {

        $this->messageManager = $messageManager;
        $this->collection = $collection;
    }

    public function aroundGetReport(
        \Magento\Framework\View\Element\UiComponent\DataProvider\CollectionFactory $subject,
        \Closure $proceed,
        $requestName
    ) {
        $result = $proceed($requestName);
        if ($requestName == 'sales_order_grid_data_source') {
            if ($result instanceof $this->collection
            ) {
                $select = $this->collection->getSelect();
                $select->join(
                    ["soi" => "sales_order_item"],
                    'main_table.entity_id = soi.order_id AND soi.product_type="simple"',
                    array('weight', 'product_type')
                )
                    ->distinct();

                $select->join(
                    ["soa" => "sales_order_address"],
                    'main_table.entity_id = soa.parent_id AND soa.address_type="shipping"',
                    array('email', 'country_id', 'postcode', 'city', 'telephone')
                )
                    ->distinct();
            }

        }
        return $this->collection;
    }
}

在这里,我们正在观察周围 getReport()方法的事件。

复制

供应商/magento/module-sales/view/adminhtml/ui_component/sales_order_grid.xml

根据您模块的范围

供应商/模块名称/视图/adminhtml/ui_component/sales_order_grid.xml

删除您复制的sales_order_grid.xml的所有内容,因为我们不想覆盖所有内容。

在模块的sales_order_grid.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">

    <columns name="sales_order_columns">

        <!-- sales_order_item weight -->
        <column name="weight">
            <argument name="data" xsi:type="array">
                <item name="config" xsi:type="array">
                    <item name="label" xsi:type="string" translate="true">Weight</item>
                    <item name="sortOrder" xsi:type="number">222</item>
                    <item name="align" xsi:type="string">right</item>
                    <item name="filter" xsi:type="string">text</item>
                    <item name="visible" xsi:type="boolean">true</item>
                    <!--<item name="bodyTmpl" xsi:type="string">ui/grid/cells/html</item>-->
                </item>
            </argument>
        </column>

        <!-- sales_order_item product_type-->
        <column name="product_type">
            <argument name="data" xsi:type="array">
                <item name="options" xsi:type="object">Vendor\ModuleName\Ui\Component\Listing\Column\ProductTypes</item>
                <item name="config" xsi:type="array">
                    <item name="label" xsi:type="string" translate="true">Product Type</item>
                    <item name="sortOrder" xsi:type="number">232</item>
                    <item name="align" xsi:type="string">right</item>
                    <!--<item name="filter" xsi:type="string">select</item>-->
                    <item name="component" xsi:type="string">Magento_Ui/js/grid/columns/select</item>
                    <item name="dataType" xsi:type="string">select</item>
                    <item name="visible" xsi:type="boolean">true</item>
                    <!--<item name="bodyTmpl" xsi:type="string">ui/grid/cells/html</item>-->
                </item>
            </argument>
        </column>

        <!-- sales_order_address country_id -->
        <column name="country_id">
            <argument name="data" xsi:type="array">
                <item name="config" xsi:type="array">
                    <item name="label" xsi:type="string" translate="true">Country ID</item>
                    <item name="sortOrder" xsi:type="number">242</item>
                    <item name="align" xsi:type="string">right</item>
                    <item name="filter" xsi:type="string">text</item>
                    <item name="visible" xsi:type="boolean">true</item>
                    <!--<item name="bodyTmpl" xsi:type="string">ui/grid/cells/html</item>-->
                </item>
            </argument>
        </column>

        <!-- sales_order_address post_code -->
        <column name="postcode">
            <argument name="data" xsi:type="array">
                <item name="config" xsi:type="array">
                    <item name="label" xsi:type="string" translate="true">Postcode</item>
                    <item name="sortOrder" xsi:type="number">252</item>
                    <item name="align" xsi:type="string">right</item>
                    <item name="filter" xsi:type="string">text</item>
                    <item name="visible" xsi:type="boolean">true</item>
                    <!--<item name="bodyTmpl" xsi:type="string">ui/grid/cells/html</item>-->
                </item>
            </argument>
        </column>

        <!-- sales_order_address city -->
        <column name="city">
            <argument name="data" xsi:type="array">
                <item name="config" xsi:type="array">
                    <item name="label" xsi:type="string" translate="true">City</item>
                    <item name="sortOrder" xsi:type="number">252</item>
                    <item name="align" xsi:type="string">right</item>
                    <item name="filter" xsi:type="string">text</item>
                    <item name="visible" xsi:type="boolean">true</item>
                    <!--<item name="bodyTmpl" xsi:type="string">ui/grid/cells/html</item>-->
                </item>
            </argument>
        </column>

        <!-- sales_order_address telephone -->
        <column name="telephone">
            <argument name="data" xsi:type="array">
                <item name="config" xsi:type="array">
                    <item name="label" xsi:type="string" translate="true">Telephone</item>
                    <item name="sortOrder" xsi:type="number">252</item>
                    <item name="align" xsi:type="string">right</item>
                    <item name="filter" xsi:type="string">text</item>
                    <item name="visible" xsi:type="boolean">true</item>
                    <!--<item name="bodyTmpl" xsi:type="string">ui/grid/cells/html</item>-->
                </item>
            </argument>
        </column>

    </columns>

</listing>

现在,从var / cache文件夹中删除缓存或刷新缓存。您将能够看到在销售订单网格中添加的列。


非常感谢那个,我唯一的问题(使用Magento 2.2.0)是我必须在行["soi" => "sales_order_item"]和上添加表前缀["soa" => "sales_order_address"]
大卫

我以为它工作正常,但似乎也与发票网格混为一谈。启用该模块后,订单ID和状态在发票网格中怪异地为空。
大卫

感谢您提供此信息,它帮助我添加了公司名称。但是,我将如何显示账单和运输信息,而不仅仅是运输?我可以显示1或另一个,但我似乎无法将“ company”重命名为“ billing_company”和“ shipping_company”,以便在sales_order_grid.xml中使用
RLTcode

1
使用插件类时,在CMS页,CMS块,客户和Creditmemo网格中出现错误,请让我知道是否有其他解决方案来修改网格集合。
维沙尔

您会看到发票网格等什么错误?
Asrar

9

当您查看\Magento\Framework\Data\Collection\AbstractDbmagento2本身时,请为您的集合提供挂钩操作。

protected function _renderFilters()
{
    if ($this->_isFiltersRendered) {
        return $this;
    }

    $this->_renderFiltersBefore(); // Hook for operations before rendering filters

    ....................
}

因此,只需添加您的收藏夹即可完成此操作[ NAMESPACE\MODULENAME\Model\ResourceModel\YOUR_CLASSNAME\Grid\Collection]

protected function _renderFiltersBefore() {
    $joinTable = $this->getTable('catalog_product_entity_varchar');
    $this->getSelect()->join($joinTable.' as cpev','main_table.entity_id = cpev.entity_id', array('*'));
    parent::_renderFiltersBefore();
}

我需要在这种情况下在订单网格中显示我的自定义表格字段以显示它吗?
Pradeep Kumar

@Keyur Shah谢谢,这对我有很大帮助。
罗希特·戈尔

很高兴听到它对您有帮助:) @RohitGoel Keep帮助其他社区成员
Keyur Shah

当然:) @KeyurShah我喜欢帮助社区。我正在创建一个不带ui组件的网格,请您告诉我如何在其中添加导出功能。
罗希特·戈尔

1
相反_renderFiltersBefore,您也可以覆盖/扩展_initSelect
贾尼斯·埃默里斯(JānisElmeris)

3

我创建了具有两个自定义表的联接的管理网格。您不能通过使用虚拟类型为di.xml来执行此操作,因此您需要按照以下步骤操作并更新您的

etc / di.xml,

Model / Resource / Modulename / Collection.php在此文件中添加联接,

型号/资源/模块名称/网格/Collection.php,

在您的etc / di.xml中

<type name="Magento\Framework\View\Element\UiComponent\DataProvider\CollectionFactory">
        <arguments>
            <argument name="collections" xsi:type="array">
                <item name="namespace_modulename_listing_data_source" xsi:type="string">Namespace\Modulename\Model\Resource\Modulename\Grid\Collection</item>
            </argument>
        </arguments>
</type>
<type name="Namespace\Modulename\Model\Resource\Modulename\Grid\Collection">
    <arguments>
        <argument name="mainTable" xsi:type="string">tablename</argument>
        <argument name="eventPrefix" xsi:type="string">namespace_modulename_grid_collection</argument>
        <argument name="eventObject" xsi:type="string">namespace_grid_collection</argument>
        <argument name="resourceModel" xsi:type="string">Namespace\Modulename\Model\Resource\Modulename</argument>
    </arguments>
</type>

在您的Model / Resource / Modulename / Collection.php中

<?php
namespace Namespace\Modulename\Model\Resource\Modulename;

use Magento\Framework\Model\ResourceModel\Db\Collection\AbstractCollection;

class Collection extends AbstractCollection
{
    /**
     * Define model & resource model
     */
    const YOUR_TABLE = 'tablename';

    public function __construct(
        \Magento\Framework\Data\Collection\EntityFactoryInterface $entityFactory,
        \Psr\Log\LoggerInterface $logger,
        \Magento\Framework\Data\Collection\Db\FetchStrategyInterface $fetchStrategy,
        \Magento\Framework\Event\ManagerInterface $eventManager,
        \Magento\Store\Model\StoreManagerInterface $storeManager,
        \Magento\Framework\DB\Adapter\AdapterInterface $connection = null,
        \Magento\Framework\Model\ResourceModel\Db\AbstractDb $resource = null
    ) {
        $this->_init(
            'Namespace\Modulename\Model\Modulename',
            'Namespace\Modulename\Model\Resource\Modulename'
        );
        parent::__construct(
            $entityFactory, $logger, $fetchStrategy, $eventManager, $connection,
            $resource
        );
        $this->storeManager = $storeManager;
    }
    protected function _initSelect()
    {
        parent::_initSelect();

        $this->getSelect()->joinLeft(
                ['secondTable' => $this->getTable('tablename')],
                'main_table.columnname = secondTable.columnname',
                ['columnname1','columnname2','columnname3']
            );
    }
}
?>

在您的Model / Resource / Modulename / Grid / Collection.php中

<?php
namespace Namespace\Modulename\Model\Resource\Modulename\Grid;

use Magento\Framework\Api\Search\SearchResultInterface;
use Magento\Framework\Search\AggregationInterface;
use Namespace\Modulename\Model\Resource\Modulename\Collection as ModulenameCollection;

/**
 * Class Collection
 * Collection for displaying grid
 */
class Collection extends ModulenameCollection implements SearchResultInterface
{
    /**
     * Resource initialization
     * @return $this
     */
   public function __construct(
        \Magento\Framework\Data\Collection\EntityFactoryInterface $entityFactory,
        \Psr\Log\LoggerInterface $logger,
        \Magento\Framework\Data\Collection\Db\FetchStrategyInterface $fetchStrategy,
        \Magento\Framework\Event\ManagerInterface $eventManager,
        \Magento\Store\Model\StoreManagerInterface $storeManager,
        $mainTable,
        $eventPrefix,
        $eventObject,
        $resourceModel,
        $model = 'Magento\Framework\View\Element\UiComponent\DataProvider\Document',
        $connection = null,
        \Magento\Framework\Model\ResourceModel\Db\AbstractDb $resource = null
    ) {
        parent::__construct(
            $entityFactory,
            $logger,
            $fetchStrategy,
            $eventManager,
            $storeManager,
            $connection,
            $resource
        );
        $this->_eventPrefix = $eventPrefix;
        $this->_eventObject = $eventObject;
        $this->_init($model, $resourceModel);
        $this->setMainTable($mainTable);
    }

    /**
     * @return AggregationInterface
     */
    public function getAggregations()
    {
        return $this->aggregations;
    }

    /**
     * @param AggregationInterface $aggregations
     *
     * @return $this
     */
    public function setAggregations($aggregations)
    {
        $this->aggregations = $aggregations;
    }


    /**
     * Get search criteria.
     *
     * @return \Magento\Framework\Api\SearchCriteriaInterface|null
     */
    public function getSearchCriteria()
    {
        return null;
    }

    /**
     * Set search criteria.
     *
     * @param \Magento\Framework\Api\SearchCriteriaInterface $searchCriteria
     *
     * @return $this
     * @SuppressWarnings(PHPMD.UnusedFormalParameter)
     */
    public function setSearchCriteria(
        \Magento\Framework\Api\SearchCriteriaInterface $searchCriteria = null
    ) {
        return $this;
    }

    /**
     * Get total count.
     *
     * @return int
     */
    public function getTotalCount()
    {
        return $this->getSize();
    }

    /**
     * Set total count.
     *
     * @param int $totalCount
     *
     * @return $this
     * @SuppressWarnings(PHPMD.UnusedFormalParameter)
     */
    public function setTotalCount($totalCount)
    {
        return $this;
    }

    /**
     * Set items list.
     *
     * @param \Magento\Framework\Api\ExtensibleDataInterface[] $items
     *
     * @return $this
     * @SuppressWarnings(PHPMD.UnusedFormalParameter)
     */
    public function setItems(array $items = null)
    {
        return $this;
    }
}

?>

它没有工作
saravanavelu's

对我来说效果很好..您的错误是什么?
Ekta Puri

内部服务器错误。您可以检查并重新格式化您的代码吗?
saravanavelu,2016年

我可以在某处查看您的文件吗?因为这完全适合我,所以我还是会再次尝试重新格式化
Ekta Puri

等/ di.xml型号/资源/ MODULENAME /收藏没有像什么在这di.xml
saravanavelu

2

在ui定义xml中,有一个与此相似的数据源节点

<dataSource name="listing_name_data_source">
    <argument name="dataProvider" xsi:type="configurableObject">
        <argument name="class" xsi:type="string">UniqueNameGridDataProvider</argument>
        <argument name="name" xsi:type="string">listing_name_data_source</argument>

listing_name_data_source可以在您的位置定义di.xml或直接引用类。该类本身应从您的自定义集合扩展Magento\Framework\View\Element\UiComponent\DataProvider\CollectionFactory并以其为collections参数。在该集合类的_initSelect()方法中,您可以连接表。


1
在sales di.xml中,它显示了Magento \ Sales \ Model \ ResourceModel \ Order \ Grid \ Collection该文件自身不会退出的位置,在这种情况下,我们无法重写插件或事件,请执行以下操作检查销售di和订单网格收集代码,我希望这会清除更多信息
Pradeep Kumar

它是在github.com/magento/magento2/blob/develop/app/code/Magento/Sales/…中定义的,并且是从Magento \ Framework \ View \ Element \ UiComponent \ DataProvider \ SearchResult
Kristof在Fooman

然后可以将join添加到该类中。您能提供示例代码吗?
Pradeep Kumar

这里以initSelect中使用的连接示例 github.com/magento/magento2/blob/develop/app/code/Magento / ... github.com/magento/magento2/blob/develop/app/code/Magento/
克里斯托夫在Fooman,2016年

@KristofatFooman您给出了错误的示例,因为它是虚拟类型,您能举一个定义为虚拟类型的网格集合示例吗?
LucScu '16

2

对于@Asrar解决方案有问题的任何人,只需执行以下操作:

public function aroundGetReport(
    \Magento\Framework\View\Element\UiComponent\DataProvider\CollectionFactory $subject,
    \Closure $proceed,
    $requestName
) {
    $result = $proceed($requestName);
    if ($requestName == 'sales_order_grid_data_source_firsty') {
        if ($result instanceof $this->collection
        ) {
            $select = $this->collection->getSelect();
            $select->join(
                ["soi" => "sales_order_item"],
                'main_table.entity_id = soi.order_id',
                array('sku', 'name','item_id')
            )
                ->distinct();
            return $this->collection;
        }

    }
    return $result;
}

这似乎对我来说还可以。

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.