GridView custom column sorting

I’m struggling to sort gridview by custom column. This attribute is calculated and does not exist in a database. Data for this attribute are created by the model. I have found and tried several solutions but failed to implement them in my situation. Also I’m wondering whether my approach to translate pack_type integer value to string value packTypeWord is correct or is there a better way to do it?

Item model

const PACK_TYPE_UNDEFINED = 0;
const PACK_TYPE_UNPACKED = 1;
const PACK_TYPE_CASE = 2;
const PACK_TYPE_PALETTE = 3;
const PACK_TYPE_STACK = 4;
const PACK_TYPE_CARTON = 5;

...

public static function getPackTypeArray()
{
    return [
        self::PACK_TYPE_UNDEFINED => '(undefined)',
        self::PACK_TYPE_UNPACKED => 'Unpacked',
        self::PACK_TYPE_CASE => 'Case',
        self::PACK_TYPE_PALETTE => 'Palette',
        self::PACK_TYPE_STACK => 'Stack',
        self::PACK_TYPE_CARTON => 'Carton',
    ];
}

public function getPackTypeWord()
{
    $types = self::getPackTypeArray();
    
    if (array_key_exists($this->pack_type, $types)) {
        return $types[$this->pack_type];
    }

    return '';
}

ItemSearch is generated by Gii, I changed function search() only by adding setSort

public function search($params)
{

     $dataProvider->setSort([
        'attributes'=>[
            'num',
            'name',
            'packTypeWord',              
        ],
        'defaultOrder' => ['num' => SORT_ASC]             
    ]);

Hi @kubove,

getPackTypeWord() looks fine to me.

Is pack_type a column in the table?
If it is, the following should work:

     $dataProvider->setSort([
        'attributes'=>[
            'num',
            'name',
            'packTypeWord' => [
                'asc' => ['pack_type' => SORT_ASC, 'num' => SORT_ASC],
                'desc' => ['pack_type' => SORT_DESC, 'num' => SORT_DESC],
            ],              
        ],
        'defaultOrder' => ['num' => SORT_ASC]             
    ]);

It doesn’t sort the records by the alphabetical order of packTypeWord, but by the integer value of pack_type. If you do want the alphabetical order, we would have to do some tricky thing that is a bit more complicated.

Hi @softark, thank you for your answer. Yes, pack_type is a column in the table. It is not necessary to have alphabetical order of packTypeWord, order by value of pack_type is enough. I made the change you proposed and it works. Thank you!