3

I have joined 2 columns to customer grid, I can make them filterable but I don't know how to make them sortable. Here is my _prepareCollection function:

protected function _prepareCollection()
  {
    $collection = Mage::getResourceModel('customer/customer_collection')
      ->addNameToSelect()
      ->addAttributeToSelect('email')
      ->addAttributeToSelect('created_at')
      ->addAttributeToSelect('group_id');
    $collection->addSalesInfoPerCustomer();
    $this->setCollection($collection);
    return parent::_prepareCollection();
  }

My joined function:

public function addSalesInfoPerCustomer() {
    $this->getSelect()
      ->joinLeft(
        array('s' => new Zend_Db_Expr('(SELECT sum(o.base_grand_total) total_sales, COUNT(*) as order_count, customer_id'
          . ' FROM ' . Mage::getSingleton('core/resource')->getTableName('sales/order') . ' AS o'
          . ' GROUP BY customer_id)')),
        "s.customer_id = e.entity_id",
        array('total_sales', 'order_count')
      );
  }

Added Column:

$this->addColumn('order_count', array(
      'header' => Mage::helper('customer')->__('Total Orders'),
      'index' => 'order_count',
      'filter_index' => 'pages_with_number_of_views.order_count',
      'filter_condition_callback' => array($this, '_roleFilter'),
    ));

    $this->addColumn('total_sales', array(
      'header' => Mage::helper('sales')->__('Total Sales'),
      'index' => 'total_sales',
      'type' => 'price',
      'currency_code' => Mage::app()->getStore()->getBaseCurrency()->getCode(),
      'filter_condition_callback' => array($this, '_roleFilterTotalSales'),
    ));

Can anyone help me please ?

1

1 Answer 1

5

I have founded the answered after a few days. The solution for this kind of problem is added this function to grid: (overwrite _setCollectionOrder in parent grid class).

protected function _setCollectionOrder($column)
  {
    $collection = $this->getCollection();
    if ($collection) {
      $columnIndex = $column->getFilterIndex() ? $column->getFilterIndex() : $column->getIndex();
      if($columnIndex == 'pages_with_number_of_views.order_count')
      {
        $columnIndex = 'order_count';
        $collection->getSelect()->order($columnIndex.' '.strtoupper($column->getDir()));
      }
      if($columnIndex == 'total_sales'){
        $collection->getSelect()->order($columnIndex.' '.strtoupper($column->getDir()));
      }
      else{
        $collection->setOrder($columnIndex, strtoupper($column->getDir()));
      }
    }
    return $this;
  }
1
  • 1
    I really appreciate this :)
    – HungDQ
    Commented Jul 15, 2015 at 2:25

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.