Yii2 gridview filter virtual attribute textfield showing a number by default

749 Views Asked by At

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)

2

There are 2 best solutions below

10
ScaisEdge On BEST ANSWER

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 ..

4
Marcin Gordel On

Filter filed is render for search model and their attributes passed to GridView. When you create that model, virtual attribute $FnGdiff is set by specified value when model is initial before send query. Your attribute $FnGdiff is deafault set 0 ($this->FnG - $this->fd, in new model it is: null - null = 0), and that value is render in text filter field. So you should return specified value only for no new record. Try this:

public function getFnGdiff() {
    return $this->isNewRecord ? '' : $this->FnG - $this->fd;
}