Example of a function for bringing the correlated field to search and sort in the Yii2-GridView, yii2gridview sorting
Situation requirements:
To display the Customer name in the Order view's gridview, and make it have the same sorting and search functions as other fields.
Database Structure
Order table order contains the customer_id field and the id field of the customer table.
First, make sure that the Order Model contains the following code:
public function getCustomer(){ return $this->hasOne(Customer::className(), ['id' => 'customer_id']);}
This code is automatically generated using gii;
Step 1:
Add a $ mermer_name variable in OrderSearch.
Class OrderSearch extends Order {public $ customer_name; // <====== is added here}
Step 2:
Modify the search function in OrderSearch
Public function search ($ params) {$ query = Order: find (); $ query-> joinWith (['customer']); <===== add this sentence $ dataProvider = new ActiveDataProvider (['query' => $ query,]); $ dataProvider-> setSort (['bubuckets' => [/* do not change other fields * // * the following section is added * // * ====== ===== */'customer _ name' => ['asc '=> ['customer. customer_name '=> SORT_ASC], 'desc' => ['customer. customer_name '=> SORT_DESC], 'label' => 'customer name' ],/* = */]); If (! ($ This-> load ($ params) & $ this-> validate () {return $ dataProvider ;} $ query-> andFilterWhere (['id' => $ this-> id, 'user _ id' => $ this-> user_id, 'Customer _ id' => $ this-> customer_id, 'order _ time' => $ this-> order_time, 'Pay _ time' => $ this-> pay_time,]); $ query-> andFilterWhere (['like', 'status', $ this-> status]); $ query-> andFilterWhere (['like', 'customer. customer_name ', $ this-> customer_name]); // <==== Add the return $ dataProvider ;}
Step 3:
Modify the order/index view's gridview
<? = GridView: widget (['dataprovider' => $ dataProvider, 'filtermodel' => $ searchModel, 'columns '=> [['class' => 'yii \ grid \ SerialColumn'], 'id', 'customer _ id', 'status ', ['label' => 'customer', 'attribute' => 'customer _ name', 'value' => 'customer. customer_name '], // <==== add this sentence to ['class' => 'yii \ grid \ ActionColumn'],],]);?>
The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.