Ravi Gohil
Ravi Gohil

Reputation: 157

Fully Custom Filter in Yii2

I have a gridview where I need to show percentage of one column with some calculation logic.

It is done, I have a numeric value in one column says "Percentage" but in table I have "mark" field only.

Now I want to add a search filter for this "percentage" field but the problem is in my table there is no percentage so when I try to search percentage it checks for marks value only.

How can I search for "percentage" value in gridview filter instead of searching on "mark" field.

https://www.screencast.com/t/IfUezWnJ

Actually I have a value in database column 'battery' like '1256' and after some calculation I show the battery percentage in gridview. but in gridview search filter I would like to search by percentage. But I could not because in table we have no percentage.

Upvotes: 1

Views: 948

Answers (1)

Take a look at this page.

The main steps are:

  1. In the base model create a virtual property (getter method) that do the calculus needed to get the percentage from real mark field: getPercentage()
  2. In the search model, add a public property (attribute) with the same name of virtual property in the base model (public $percentage)
  3. In the rules method, add a safe validator for this new property.
  4. In the search method, add the proper where clause into the query. This can by a bit tricky if the percent calc is complex or involves subqueries. A simple case would be if the percentage is obtained from another field, let's say max_value. In this case you can use a line like: $query->andWhere ('ilike','mark',$this->percentage/100*max_value) (Is only a example. Surely ilike is not the best operator for this condition.)
  5. Use the virtual field in the gridview widget.

If you need a subquery or with statement to get the percentage, you'll need add some additional sentences into $query object, but the main steps are the same.

If you want add sorting capabilities into gridview widget you must define how to order and use expressions if necessary. Tale a look to this link

Upvotes: 1

Related Questions