How to order or filter grid backend magento with collection

In magento 2 , if  you join the tables and display them  in the grid backend magento  but when to sort or filter them, you found an” field not found” error.

For example we have 2 tables:

Table 1 has name” customer” field “name”, “gender’’,” age “.

Table 2 has name “address” field” address”, ”city”, ”country”.

Whereas you join table 1 and table 2 collections and display them in the grid backend magento .

If you want to sort or filter the “address”, “city”, “country” you should override “add field to filter” ,“sort order” and “add order” function”.

  * @param mixed $field

 * @param null $condition

 * @return $this|\Magento\Framework\Data\Collection\AbstractDb

 */

 public function addFieldToFilter($field, $condition = null)

{

 if($field == address)

  $field = address.address;

  if($field == city)

  $field = address.city;

  if($field == country)

  $field = address.country;

  return parent::addFieldToFilter($field, $condition);

  }

/**

 * @param string $field

 * @param string $direction

 * @return $this

 */

 public function addOrder($field, $direction = self::SORT_ORDER_DESC)

{

  if($field == address)

 $field = address.address;

 if($field == city)

 $field = address.city;

  if($field == country)

   $field = address.country;

   if($field == 'warehouse_product.total_qty') {

  return $this->sortByTotalQty($field, $direction);

}

  return parent::addOrder($field, $direction);

 }

  /**

   * Add select order

  * @param   string $field

 * @param   string $direction

 * @return  $this

*/

 public function setOrder($field, $direction = self::SORT_ORDER_DESC)

 {

   if($field == address)

  $field = address.address;

if($field == city)

  $field = address.city;

  if($field == country)

  $field = address.country;

     return parent::setOrder($field, $direction);

  }

I hope the above mentioned steps will help you to order or filter grid backend magento with collection which is joined from multiple tables easily. All store has order or filter grid backend magento  with collection which Is joined from multiple tables in magento  with multiple elements.

Last Update: April 9, 2018  

February 6, 2018   319   Nandini R    Operations    
Total 1 Votes:
1

Tell us how can we improve this post?

+ = Verify Human or Spambot ?

Leave a Reply

Your email address will not be published. Required fields are marked *

Facebook
Twitter
INSTAGRAM
LinkedIn