Magento 2: Sorting is not working while adding custom column in Order Grid Using Ui Component












3















I want to add a custom column in order grid with sorting enabled in it.



For now, I am including a column which shows the color attribute of the product in that order.



This is the file sales_order_grid.xml file created in app/code/VENDOR/MODULE/view/adminhtml/ui_component/



below is the code



<?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">
<column name="color" class="VENDORMODULEUiComponentListingColumnColor">
<argument name="data" xsi:type="array">
<item name="config" xsi:type="array">
<item name="label" xsi:type="string" translate="true">Color</item>
<item name="sortable" xsi:type="boolean">false</item>
<item name="filter" xsi:type="string">text</item>
</item>
</argument>
</column>
</columns>
</listing>


And app/code/VENDOR/MODULE/Ui/Component/Listing/Column/Color.php



<?php
namespace VENDORMODULEUiComponentListingColumn;
use MagentoFrameworkViewElementUiComponentContextInterface;
use MagentoFrameworkViewElementUiComponentFactory;
class Color extends MagentoUiComponentListingColumnsColumn
{
/**
* @var MagentoCatalogModelOrderFactory
*/
protected $_orderFactory;

/**
* @var MagentoCatalogModelProductRepository
*/
protected $productFactory;

/**
*
* @param ContextInterface $context
* @param UiComponentFactory $uiComponentFactory
* @param array $components
* @param array $data
*/
public function __construct(
ContextInterface $context,
UiComponentFactory $uiComponentFactory,
MagentoSalesModelOrderFactory $orderFactory,
MagentoCatalogModelProductFactory $productFactory,
array $components = ,
array $data =
) {
parent::__construct($context, $uiComponentFactory, $components, $data);
$this->_orderFactory = $orderFactory;
$this->_productFactory = $productFactory;
}

/**
* Prepare Data Source
*
* @param array $dataSource
* @return array
*/
public function prepareDataSource(array $dataSource)
{
if (isset($dataSource['data']['items'])) {
foreach ($dataSource['data']['items'] as & $item) {
//Get order details by order id.
$order = $this->_orderFactory->create()->load($item['entity_id']);

//Get all products in this order.
$products = $order->getAllItems();
foreach ($products as $product) {
$productId = $product->getProductId();
$productData = $this->_productFactory->create()->load($productId);
$item['color'] = $productData->getResource()->getAttribute('color')->getFrontend()->getValue($productData);
}
}
}

return $dataSource;
}
}


Now when I perform sorting over this it gives following as color column is not related to order:



2 exception(s): Exception #0 (Zend_Db_Statement_Exception): SQLSTATE[42S22]: Column not found: 1054 Unknown column 'color' in 'order clause', query was: SELECT `main_table`.* FROM `sales_order_grid` AS `main_table` ORDER BY color ASC  LIMIT 20 Exception #1 (PDOException): SQLSTATE[42S22]: Column not found: 1054 Unknown column 'color' in 'order clause'

Exception #0 (Zend_Db_Statement_Exception): SQLSTATE[42S22]: Column not found: 1054 Unknown column 'color' in 'order clause', query was: SELECT `main_table`.* FROM `sales_order_grid` AS `main_table` ORDER BY color ASC LIMIT 20
#0 /opt/lampp/htdocs/magento2/vendor/magento/framework/DB/Statement/Pdo/Mysql.php(95): Zend_Db_Statement_Pdo->_execute(Array)
#1 /opt/lampp/htdocs/magento2/vendor/magento/zendframework1/library/Zend/Db/Statement.php(303): MagentoFrameworkDBStatementPdoMysql->_execute(Array)
#2 /opt/lampp/htdocs/magento2/vendor/magento/zendframework1/library/Zend/Db/Adapter/Abstract.php(480): Zend_Db_Statement->execute(Array)
#3 /opt/lampp/htdocs/magento2/vendor/magento/zendframework1/library/Zend/Db/Adapter/Pdo/Abstract.php(238): Zend_Db_Adapter_Abstract->query('SELECT `main_ta...', Array)


Same case when applying a filter, so how to perform this.










share|improve this question
















bumped to the homepage by Community 7 mins ago


This question has answers that may be good or bad; the system has marked it active so that they can be reviewed.




















    3















    I want to add a custom column in order grid with sorting enabled in it.



    For now, I am including a column which shows the color attribute of the product in that order.



    This is the file sales_order_grid.xml file created in app/code/VENDOR/MODULE/view/adminhtml/ui_component/



    below is the code



    <?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">
    <column name="color" class="VENDORMODULEUiComponentListingColumnColor">
    <argument name="data" xsi:type="array">
    <item name="config" xsi:type="array">
    <item name="label" xsi:type="string" translate="true">Color</item>
    <item name="sortable" xsi:type="boolean">false</item>
    <item name="filter" xsi:type="string">text</item>
    </item>
    </argument>
    </column>
    </columns>
    </listing>


    And app/code/VENDOR/MODULE/Ui/Component/Listing/Column/Color.php



    <?php
    namespace VENDORMODULEUiComponentListingColumn;
    use MagentoFrameworkViewElementUiComponentContextInterface;
    use MagentoFrameworkViewElementUiComponentFactory;
    class Color extends MagentoUiComponentListingColumnsColumn
    {
    /**
    * @var MagentoCatalogModelOrderFactory
    */
    protected $_orderFactory;

    /**
    * @var MagentoCatalogModelProductRepository
    */
    protected $productFactory;

    /**
    *
    * @param ContextInterface $context
    * @param UiComponentFactory $uiComponentFactory
    * @param array $components
    * @param array $data
    */
    public function __construct(
    ContextInterface $context,
    UiComponentFactory $uiComponentFactory,
    MagentoSalesModelOrderFactory $orderFactory,
    MagentoCatalogModelProductFactory $productFactory,
    array $components = ,
    array $data =
    ) {
    parent::__construct($context, $uiComponentFactory, $components, $data);
    $this->_orderFactory = $orderFactory;
    $this->_productFactory = $productFactory;
    }

    /**
    * Prepare Data Source
    *
    * @param array $dataSource
    * @return array
    */
    public function prepareDataSource(array $dataSource)
    {
    if (isset($dataSource['data']['items'])) {
    foreach ($dataSource['data']['items'] as & $item) {
    //Get order details by order id.
    $order = $this->_orderFactory->create()->load($item['entity_id']);

    //Get all products in this order.
    $products = $order->getAllItems();
    foreach ($products as $product) {
    $productId = $product->getProductId();
    $productData = $this->_productFactory->create()->load($productId);
    $item['color'] = $productData->getResource()->getAttribute('color')->getFrontend()->getValue($productData);
    }
    }
    }

    return $dataSource;
    }
    }


    Now when I perform sorting over this it gives following as color column is not related to order:



    2 exception(s): Exception #0 (Zend_Db_Statement_Exception): SQLSTATE[42S22]: Column not found: 1054 Unknown column 'color' in 'order clause', query was: SELECT `main_table`.* FROM `sales_order_grid` AS `main_table` ORDER BY color ASC  LIMIT 20 Exception #1 (PDOException): SQLSTATE[42S22]: Column not found: 1054 Unknown column 'color' in 'order clause'

    Exception #0 (Zend_Db_Statement_Exception): SQLSTATE[42S22]: Column not found: 1054 Unknown column 'color' in 'order clause', query was: SELECT `main_table`.* FROM `sales_order_grid` AS `main_table` ORDER BY color ASC LIMIT 20
    #0 /opt/lampp/htdocs/magento2/vendor/magento/framework/DB/Statement/Pdo/Mysql.php(95): Zend_Db_Statement_Pdo->_execute(Array)
    #1 /opt/lampp/htdocs/magento2/vendor/magento/zendframework1/library/Zend/Db/Statement.php(303): MagentoFrameworkDBStatementPdoMysql->_execute(Array)
    #2 /opt/lampp/htdocs/magento2/vendor/magento/zendframework1/library/Zend/Db/Adapter/Abstract.php(480): Zend_Db_Statement->execute(Array)
    #3 /opt/lampp/htdocs/magento2/vendor/magento/zendframework1/library/Zend/Db/Adapter/Pdo/Abstract.php(238): Zend_Db_Adapter_Abstract->query('SELECT `main_ta...', Array)


    Same case when applying a filter, so how to perform this.










    share|improve this question
















    bumped to the homepage by Community 7 mins ago


    This question has answers that may be good or bad; the system has marked it active so that they can be reviewed.


















      3












      3








      3








      I want to add a custom column in order grid with sorting enabled in it.



      For now, I am including a column which shows the color attribute of the product in that order.



      This is the file sales_order_grid.xml file created in app/code/VENDOR/MODULE/view/adminhtml/ui_component/



      below is the code



      <?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">
      <column name="color" class="VENDORMODULEUiComponentListingColumnColor">
      <argument name="data" xsi:type="array">
      <item name="config" xsi:type="array">
      <item name="label" xsi:type="string" translate="true">Color</item>
      <item name="sortable" xsi:type="boolean">false</item>
      <item name="filter" xsi:type="string">text</item>
      </item>
      </argument>
      </column>
      </columns>
      </listing>


      And app/code/VENDOR/MODULE/Ui/Component/Listing/Column/Color.php



      <?php
      namespace VENDORMODULEUiComponentListingColumn;
      use MagentoFrameworkViewElementUiComponentContextInterface;
      use MagentoFrameworkViewElementUiComponentFactory;
      class Color extends MagentoUiComponentListingColumnsColumn
      {
      /**
      * @var MagentoCatalogModelOrderFactory
      */
      protected $_orderFactory;

      /**
      * @var MagentoCatalogModelProductRepository
      */
      protected $productFactory;

      /**
      *
      * @param ContextInterface $context
      * @param UiComponentFactory $uiComponentFactory
      * @param array $components
      * @param array $data
      */
      public function __construct(
      ContextInterface $context,
      UiComponentFactory $uiComponentFactory,
      MagentoSalesModelOrderFactory $orderFactory,
      MagentoCatalogModelProductFactory $productFactory,
      array $components = ,
      array $data =
      ) {
      parent::__construct($context, $uiComponentFactory, $components, $data);
      $this->_orderFactory = $orderFactory;
      $this->_productFactory = $productFactory;
      }

      /**
      * Prepare Data Source
      *
      * @param array $dataSource
      * @return array
      */
      public function prepareDataSource(array $dataSource)
      {
      if (isset($dataSource['data']['items'])) {
      foreach ($dataSource['data']['items'] as & $item) {
      //Get order details by order id.
      $order = $this->_orderFactory->create()->load($item['entity_id']);

      //Get all products in this order.
      $products = $order->getAllItems();
      foreach ($products as $product) {
      $productId = $product->getProductId();
      $productData = $this->_productFactory->create()->load($productId);
      $item['color'] = $productData->getResource()->getAttribute('color')->getFrontend()->getValue($productData);
      }
      }
      }

      return $dataSource;
      }
      }


      Now when I perform sorting over this it gives following as color column is not related to order:



      2 exception(s): Exception #0 (Zend_Db_Statement_Exception): SQLSTATE[42S22]: Column not found: 1054 Unknown column 'color' in 'order clause', query was: SELECT `main_table`.* FROM `sales_order_grid` AS `main_table` ORDER BY color ASC  LIMIT 20 Exception #1 (PDOException): SQLSTATE[42S22]: Column not found: 1054 Unknown column 'color' in 'order clause'

      Exception #0 (Zend_Db_Statement_Exception): SQLSTATE[42S22]: Column not found: 1054 Unknown column 'color' in 'order clause', query was: SELECT `main_table`.* FROM `sales_order_grid` AS `main_table` ORDER BY color ASC LIMIT 20
      #0 /opt/lampp/htdocs/magento2/vendor/magento/framework/DB/Statement/Pdo/Mysql.php(95): Zend_Db_Statement_Pdo->_execute(Array)
      #1 /opt/lampp/htdocs/magento2/vendor/magento/zendframework1/library/Zend/Db/Statement.php(303): MagentoFrameworkDBStatementPdoMysql->_execute(Array)
      #2 /opt/lampp/htdocs/magento2/vendor/magento/zendframework1/library/Zend/Db/Adapter/Abstract.php(480): Zend_Db_Statement->execute(Array)
      #3 /opt/lampp/htdocs/magento2/vendor/magento/zendframework1/library/Zend/Db/Adapter/Pdo/Abstract.php(238): Zend_Db_Adapter_Abstract->query('SELECT `main_ta...', Array)


      Same case when applying a filter, so how to perform this.










      share|improve this question
















      I want to add a custom column in order grid with sorting enabled in it.



      For now, I am including a column which shows the color attribute of the product in that order.



      This is the file sales_order_grid.xml file created in app/code/VENDOR/MODULE/view/adminhtml/ui_component/



      below is the code



      <?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">
      <column name="color" class="VENDORMODULEUiComponentListingColumnColor">
      <argument name="data" xsi:type="array">
      <item name="config" xsi:type="array">
      <item name="label" xsi:type="string" translate="true">Color</item>
      <item name="sortable" xsi:type="boolean">false</item>
      <item name="filter" xsi:type="string">text</item>
      </item>
      </argument>
      </column>
      </columns>
      </listing>


      And app/code/VENDOR/MODULE/Ui/Component/Listing/Column/Color.php



      <?php
      namespace VENDORMODULEUiComponentListingColumn;
      use MagentoFrameworkViewElementUiComponentContextInterface;
      use MagentoFrameworkViewElementUiComponentFactory;
      class Color extends MagentoUiComponentListingColumnsColumn
      {
      /**
      * @var MagentoCatalogModelOrderFactory
      */
      protected $_orderFactory;

      /**
      * @var MagentoCatalogModelProductRepository
      */
      protected $productFactory;

      /**
      *
      * @param ContextInterface $context
      * @param UiComponentFactory $uiComponentFactory
      * @param array $components
      * @param array $data
      */
      public function __construct(
      ContextInterface $context,
      UiComponentFactory $uiComponentFactory,
      MagentoSalesModelOrderFactory $orderFactory,
      MagentoCatalogModelProductFactory $productFactory,
      array $components = ,
      array $data =
      ) {
      parent::__construct($context, $uiComponentFactory, $components, $data);
      $this->_orderFactory = $orderFactory;
      $this->_productFactory = $productFactory;
      }

      /**
      * Prepare Data Source
      *
      * @param array $dataSource
      * @return array
      */
      public function prepareDataSource(array $dataSource)
      {
      if (isset($dataSource['data']['items'])) {
      foreach ($dataSource['data']['items'] as & $item) {
      //Get order details by order id.
      $order = $this->_orderFactory->create()->load($item['entity_id']);

      //Get all products in this order.
      $products = $order->getAllItems();
      foreach ($products as $product) {
      $productId = $product->getProductId();
      $productData = $this->_productFactory->create()->load($productId);
      $item['color'] = $productData->getResource()->getAttribute('color')->getFrontend()->getValue($productData);
      }
      }
      }

      return $dataSource;
      }
      }


      Now when I perform sorting over this it gives following as color column is not related to order:



      2 exception(s): Exception #0 (Zend_Db_Statement_Exception): SQLSTATE[42S22]: Column not found: 1054 Unknown column 'color' in 'order clause', query was: SELECT `main_table`.* FROM `sales_order_grid` AS `main_table` ORDER BY color ASC  LIMIT 20 Exception #1 (PDOException): SQLSTATE[42S22]: Column not found: 1054 Unknown column 'color' in 'order clause'

      Exception #0 (Zend_Db_Statement_Exception): SQLSTATE[42S22]: Column not found: 1054 Unknown column 'color' in 'order clause', query was: SELECT `main_table`.* FROM `sales_order_grid` AS `main_table` ORDER BY color ASC LIMIT 20
      #0 /opt/lampp/htdocs/magento2/vendor/magento/framework/DB/Statement/Pdo/Mysql.php(95): Zend_Db_Statement_Pdo->_execute(Array)
      #1 /opt/lampp/htdocs/magento2/vendor/magento/zendframework1/library/Zend/Db/Statement.php(303): MagentoFrameworkDBStatementPdoMysql->_execute(Array)
      #2 /opt/lampp/htdocs/magento2/vendor/magento/zendframework1/library/Zend/Db/Adapter/Abstract.php(480): Zend_Db_Statement->execute(Array)
      #3 /opt/lampp/htdocs/magento2/vendor/magento/zendframework1/library/Zend/Db/Adapter/Pdo/Abstract.php(238): Zend_Db_Adapter_Abstract->query('SELECT `main_ta...', Array)


      Same case when applying a filter, so how to perform this.







      magento2 magento-2.1






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited May 23 '18 at 12:19









      Mohit Kumar Arora

      6,51841632




      6,51841632










      asked Sep 4 '17 at 11:55







      user56654












      bumped to the homepage by Community 7 mins ago


      This question has answers that may be good or bad; the system has marked it active so that they can be reviewed.







      bumped to the homepage by Community 7 mins ago


      This question has answers that may be good or bad; the system has marked it active so that they can be reviewed.
























          2 Answers
          2






          active

          oldest

          votes


















          0














          Override "MagentoSalesModelResourceModelOrderGridCollection.php" and then need to create below code in that file.



          protected function _initSelect()
          {
          parent::_initSelect();

          //do your sql join like below code
          /*$this->getSelect()->joinLeft(
          ['secondTable' => $this->getTable('secondTable')],
          'main_table.entity_id = secondTable.entity_id',
          array('*')
          );*/
          }


          Hope this helps






          share|improve this answer































            0














            You are getting this error because the magento is looking for 'color' column in sales_order table which it cannot find.



            You will have to either provide custom dataprovider for the column or append these values in the respective rows of the table after adding a new 'color' column.






            share|improve this answer























              Your Answer








              StackExchange.ready(function() {
              var channelOptions = {
              tags: "".split(" "),
              id: "479"
              };
              initTagRenderer("".split(" "), "".split(" "), channelOptions);

              StackExchange.using("externalEditor", function() {
              // Have to fire editor after snippets, if snippets enabled
              if (StackExchange.settings.snippets.snippetsEnabled) {
              StackExchange.using("snippets", function() {
              createEditor();
              });
              }
              else {
              createEditor();
              }
              });

              function createEditor() {
              StackExchange.prepareEditor({
              heartbeatType: 'answer',
              autoActivateHeartbeat: false,
              convertImagesToLinks: false,
              noModals: true,
              showLowRepImageUploadWarning: true,
              reputationToPostImages: null,
              bindNavPrevention: true,
              postfix: "",
              imageUploader: {
              brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
              contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
              allowUrls: true
              },
              onDemand: true,
              discardSelector: ".discard-answer"
              ,immediatelyShowMarkdownHelp:true
              });


              }
              });














              draft saved

              draft discarded


















              StackExchange.ready(
              function () {
              StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fmagento.stackexchange.com%2fquestions%2f191847%2fmagento-2-sorting-is-not-working-while-adding-custom-column-in-order-grid-using%23new-answer', 'question_page');
              }
              );

              Post as a guest















              Required, but never shown
























              2 Answers
              2






              active

              oldest

              votes








              2 Answers
              2






              active

              oldest

              votes









              active

              oldest

              votes






              active

              oldest

              votes









              0














              Override "MagentoSalesModelResourceModelOrderGridCollection.php" and then need to create below code in that file.



              protected function _initSelect()
              {
              parent::_initSelect();

              //do your sql join like below code
              /*$this->getSelect()->joinLeft(
              ['secondTable' => $this->getTable('secondTable')],
              'main_table.entity_id = secondTable.entity_id',
              array('*')
              );*/
              }


              Hope this helps






              share|improve this answer




























                0














                Override "MagentoSalesModelResourceModelOrderGridCollection.php" and then need to create below code in that file.



                protected function _initSelect()
                {
                parent::_initSelect();

                //do your sql join like below code
                /*$this->getSelect()->joinLeft(
                ['secondTable' => $this->getTable('secondTable')],
                'main_table.entity_id = secondTable.entity_id',
                array('*')
                );*/
                }


                Hope this helps






                share|improve this answer


























                  0












                  0








                  0







                  Override "MagentoSalesModelResourceModelOrderGridCollection.php" and then need to create below code in that file.



                  protected function _initSelect()
                  {
                  parent::_initSelect();

                  //do your sql join like below code
                  /*$this->getSelect()->joinLeft(
                  ['secondTable' => $this->getTable('secondTable')],
                  'main_table.entity_id = secondTable.entity_id',
                  array('*')
                  );*/
                  }


                  Hope this helps






                  share|improve this answer













                  Override "MagentoSalesModelResourceModelOrderGridCollection.php" and then need to create below code in that file.



                  protected function _initSelect()
                  {
                  parent::_initSelect();

                  //do your sql join like below code
                  /*$this->getSelect()->joinLeft(
                  ['secondTable' => $this->getTable('secondTable')],
                  'main_table.entity_id = secondTable.entity_id',
                  array('*')
                  );*/
                  }


                  Hope this helps







                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered Jan 22 '18 at 9:46









                  Nilesh GosaiNilesh Gosai

                  619410




                  619410

























                      0














                      You are getting this error because the magento is looking for 'color' column in sales_order table which it cannot find.



                      You will have to either provide custom dataprovider for the column or append these values in the respective rows of the table after adding a new 'color' column.






                      share|improve this answer




























                        0














                        You are getting this error because the magento is looking for 'color' column in sales_order table which it cannot find.



                        You will have to either provide custom dataprovider for the column or append these values in the respective rows of the table after adding a new 'color' column.






                        share|improve this answer


























                          0












                          0








                          0







                          You are getting this error because the magento is looking for 'color' column in sales_order table which it cannot find.



                          You will have to either provide custom dataprovider for the column or append these values in the respective rows of the table after adding a new 'color' column.






                          share|improve this answer













                          You are getting this error because the magento is looking for 'color' column in sales_order table which it cannot find.



                          You will have to either provide custom dataprovider for the column or append these values in the respective rows of the table after adding a new 'color' column.







                          share|improve this answer












                          share|improve this answer



                          share|improve this answer










                          answered Jan 22 '18 at 10:33









                          Vivek KumarVivek Kumar

                          2,4522629




                          2,4522629






























                              draft saved

                              draft discarded




















































                              Thanks for contributing an answer to Magento Stack Exchange!


                              • Please be sure to answer the question. Provide details and share your research!

                              But avoid



                              • Asking for help, clarification, or responding to other answers.

                              • Making statements based on opinion; back them up with references or personal experience.


                              To learn more, see our tips on writing great answers.




                              draft saved


                              draft discarded














                              StackExchange.ready(
                              function () {
                              StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fmagento.stackexchange.com%2fquestions%2f191847%2fmagento-2-sorting-is-not-working-while-adding-custom-column-in-order-grid-using%23new-answer', 'question_page');
                              }
                              );

                              Post as a guest















                              Required, but never shown





















































                              Required, but never shown














                              Required, but never shown












                              Required, but never shown







                              Required, but never shown

































                              Required, but never shown














                              Required, but never shown












                              Required, but never shown







                              Required, but never shown







                              Popular posts from this blog

                              Polycentropodidae

                              Magento 2 Error message: Invalid state change requested

                              Paulmy