gridviewyii2filteringvirtual-attribute

Yii2 gridview filter virtual attribute textfield showing a number by default


Model:

public $FnGdiff;

public function getFnGdiff() {
    return $this->FnG - $this->fd;
}

ModelSearch:

public function rules() {
    return [
        [['fnGdiff'], 'safe'],
    ];
}

now if I add fnGdiff to gridview, there is always a number(?!) by default in the textfield where we can do filtering. It is zero, -6, etc. Is it a feature, or a bug, or have I forgotten something to adjust? Many thanks in advance!

SOLUTION:

Model:

public function getFnGdiff() {
    return $this->FnG - $this->fd;
}

ModelSearch:

public $fnGdiff;

public function rules() {
    return [
        [['fnGdiff'], 'safe'],
    ];
}
...

(So this strange number is disappeared, however it's not possible to filter a calculated virtual attribute this way, you have to select such a field from DB in order to be able to do that)


Solution

  • If you add fnGdiff t your gridView .. you invoke the function getFnGdiff() .. that seems return 0 by default ..

     could be You want show  $FnGdiff
    

    be careful with naming convention for function and vars

        'columns' => [
            ['class' => 'yii\grid\SerialColumn'],
            .....
            'FnGdiff',   // $FnGdiff content
            'fnGdiff',  // function getFnGdiff() result 
    

    and you should move the code for vars and function to searchModel

    ModelSearch

     public $FnGdiff;
    
     public function getFnGdiff() {
       return $this->FnG - $this->fd;
    }
    

    and remove this code from model ..