yii2 hinzufügen Spalte in der gridview-von-relation und die Sortierung in gridview

Habe ich 2 Probleme...

Habe ich 3 Tabellen. tbl_target_cities, lib_cities und lib_provinces.

Indem Sie die folgenden ein video-tutorial, ich war in der Lage, die Anzeige von Daten aus der tbl_target_cities, um die gridview und auch verbinden Sie es mit lib_cities.

Sortierung in der gridview-funktioniert perfekt, außer die STADT/GEMEINDE Spalte, das aus der Beziehung.

Frage 1:, Wie Sie in der richtigen Sortierung der STADT/GEMEINDE Spalte?

Frage 2: hinzufügen Provinz Spalte mit Suchbox und funktionierende Sortier-Funktion?

tbl_target_cities

+-------------------+-----------------------+
| Field             | Type                  |
+-------------------+-----------------------+
| id                | int(11)               |
| city_code         | varchar(20)           |
| kc_classification | varchar(100)          |
| cluster           | enum('1','2','3','4') |
| grouping          | int(11)               |
| priority          | varchar(100)          |
| launch_year       | int(11)               |
+-------------------+-----------------------+

lib_cities

+---------------+--------------+------+-----+---------+-------+
| Field         | Type         | Null | Key | Default | Extra |
+---------------+--------------+------+-----+---------+-------+
| city_code     | char(9)      | NO   | PRI |         |       |
| city_name     | varchar(100) | NO   | MUL | NULL    |       |
| prov_code     | char(9)      | NO   | MUL | NULL    |       |
| is_Urban      | tinyint(1)   | YES  |     | 0       |       |
| locked        | tinyint(1)   | YES  |     | 0       |       |
| app_target_hh | int(5)       | YES  |     | NULL    |       |
| 4p_areas      | tinyint(1)   | NO   |     | NULL    |       |
+---------------+--------------+------+-----+---------+-------+

lib_provinces

+-------------+-------------+------+-----+---------+-------+
| Field       | Type        | Null | Key | Default | Extra |
+-------------+-------------+------+-----+---------+-------+
| prov_code   | char(9)     | NO   | PRI |         |       |
| prov_name   | varchar(60) | NO   | MUL | NULL    |       |
| region_code | char(9)     | NO   | MUL | NULL    |       |
+-------------+-------------+------+-----+---------+-------+

TblTargetCities Modell

<?php

namespace backend\models;

use Yii;

/**
 * This is the model class for table "tbl_target_cities".
 *
 * @property integer $id
 * @property string $city_code
 * @property string $kc_classification
 * @property string $cluster
 * @property integer $grouping
 * @property string $priority
 * @property integer $launch_year
 */
class TblTargetCities extends \yii\db\ActiveRecord
{

    public $province;
    public $region;

    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'tbl_target_cities';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['region', 'kc_classification', 'cluster', 'grouping', 'priority', 'launch_year'], 'required'],
            [['cluster','province','region'], 'string'],
            [['grouping', 'launch_year'], 'integer'],
            [['city_code'], 'string', 'max' => 20],
            [['city_code'], 'required', 'message' => 'Please select a city or municipality.'],
            [['kc_classification', 'priority'], 'string', 'max' => 100],
            [['city_code'], 'unique','message'=>'City/Municipality is already covered.'],
            [['province'], 'required','message'=>'You need to select province.'],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'cityName.province.prov_name'=>'Province',//son2x:from the view.php file
            'id'=>'City /Municipality',//son2x:from the view.php file
            'city_code' => 'City /Municipality',
            'kc_classification' => 'Kc Classification',
            'cluster' => 'Cluster',
            'grouping' => 'Grouping',
            'priority' => 'Priority',
            'launch_year' => 'Launch Year',
        ];
    }

     public static function get_cities($prov_code){
        $select = "SELECT * FROM lib_cities where prov_code=$prov_code";
        $query = Yii::$app->db->createCommand($select)->queryAll();
        return $query;
    }

    //the first that works
    /*public function getCityName()
    {
      return $this->hasOne(LibCities::className(),['city_code'=>'city_code']);
    }*/

      public function getCityName()
      {
        return $this->hasOne(LibCities::className(),['city_code'=>'city_code'])->with(['province']);
      }

}

Tbl_TargetCitiesSearch Modell

<?php

namespace backend\models;

use Yii;
use yii\base\Model;
use yii\data\ActiveDataProvider;
use backend\models\TblTargetCities;

/**
 * TblTargetCitiesSearch represents the model behind the search form about `backend\models\TblTargetCities`.
 */
class TblTargetCitiesSearch extends TblTargetCities
{
    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [[ 'grouping', 'launch_year'], 'integer'],
            [['id','city_code', 'kc_classification', 'cluster', 'priority'], 'safe'],
        ];
    }

    /**
     * @inheritdoc
     */
    public function scenarios()
    {
        //bypass scenarios() implementation in the parent class
        return Model::scenarios();
    }

    /**
     * Creates data provider instance with search query applied
     *
     * @param array $params
     *
     * @return ActiveDataProvider
     */
    public function search($params)
    {
        $query = TblTargetCities::find();

        $dataProvider = new ActiveDataProvider([
            'query' => $query,
        ]);

        $this->load($params);

        if (!$this->validate()) {
            //uncomment the following line if you do not want to any records when validation fails
            //$query->where('0=1');
            return $dataProvider;
        }

        $query->joinWith('cityName');

        $query->andFilterWhere([
            'id' => $this->id,
            'grouping' => $this->grouping,
            'launch_year' => $this->launch_year,
        ]);

       /* $query->andFilterWhere(['like', 'city_code', $this->city_code])
            ->andFilterWhere(['like', 'kc_classification', $this->kc_classification])
            ->andFilterWhere(['like', 'cluster', $this->cluster])
            ->andFilterWhere(['like', 'priority', $this->priority]);   */

        $query->andFilterWhere(['like', 'kc_classification', $this->kc_classification])
            ->andFilterWhere(['like', 'cluster', $this->cluster])
            ->andFilterWhere(['like', 'priority', $this->priority])
            ->andFilterWhere(['like', 'lib_cities.city_name', $this->city_code]);


        return $dataProvider;
    }

}

LibCities Modell

<?php

namespace backend\models;

use Yii;

/**
 * This is the model class for table "lib_cities".
 *
 * @property string $city_code
 * @property string $city_name
 * @property string $prov_code
 * @property integer $is_Urban
 * @property integer $locked
 * @property integer $app_target_hh
 * @property integer $4p_areas
 */
class LibCities extends \yii\db\ActiveRecord
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'lib_cities';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['city_code', 'city_name', 'prov_code', '4p_areas'], 'required'],
            [['is_Urban', 'locked', 'app_target_hh', '4p_areas'], 'integer'],
            [['city_code', 'prov_code'], 'string', 'max' => 9],
            [['city_name'], 'string', 'max' => 100]
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'city_code' => 'City Code',
            'city_name' => 'City Name',
            'prov_code' => 'Prov Code',
            'is_Urban' => 'Is  Urban',
            'locked' => 'Locked',
            'app_target_hh' => 'App Target Hh',
            '4p_areas' => '4p Areas',
        ];
    }

    public function getProvince()
    {
      return $this->hasOne(LibProvinces::className(),['prov_code'=>'prov_code']);
    }



}

LibProvinces Modell

<?php

namespace backend\models;

use Yii;

/**
 * This is the model class for table "lib_provinces".
 *
 * @property string $prov_code
 * @property string $prov_name
 * @property string $region_code
 */
class LibProvinces extends \yii\db\ActiveRecord
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'lib_provinces';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['prov_code', 'prov_name', 'region_code'], 'required'],
            [['prov_code', 'region_code'], 'string', 'max' => 9],
            [['prov_name'], 'string', 'max' => 60]
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'prov_code' => 'Prov Code',
            'prov_name' => 'Prov Name',
            'region_code' => 'Region Code',
        ];
    }
}

Index.php Datei

<?php

use yii\helpers\Html;
use yii\grid\GridView;

/* @var $this yii\web\View */
/* @var $searchModel backend\models\TblTargetCitiesSearch */
/* @var $dataProvider yii\data\ActiveDataProvider */

$this->title = 'Coverage';
$this->params['breadcrumbs'][] = $this->title;
?>
<div class="tbl-target-cities-index">

    <h1><?= Html::encode($this->title) ?></h1>
    <?php //echo $this->render('_search', ['model' => $searchModel]); ?>

    <p>
        <?= Html::a('Add new City/Municipality', ['create'], ['class' => 'btn btn-success']) ?>
    </p>

    <?= GridView::widget([
        'dataProvider' => $dataProvider,
        'filterModel' => $searchModel,
        'columns' => [
            ['class' => 'yii\grid\SerialColumn'],

            [
                'attribute'=>'city_code',
                'value'=>'cityName.city_name',
                //'contentOptions'=>['style'=>'width: 120px;']
            ],
            [
              'attribute'=>'kc_classification',
              //'contentOptions'=>['style'=>'width: 120px;']
            ],
            [
                'attribute'=>'cluster',
                //'contentOptions'=>['style'=>'max-width: 100px;']
            ],
            'grouping',
             'priority',
            'launch_year',

            ['class' => 'yii\grid\ActionColumn',
            'contentOptions'=>['style'=>'width: 70px;']],
        ],
    ]); ?>

</div>

BEISPIEL ANZEIGEN AUFSTEIGEND - (funktioniert nicht richtig).

yii2 hinzufügen Spalte in der gridview-von-relation und die Sortierung in gridview

IN ABSTEIGENDER REIHENFOLGE

yii2 hinzufügen Spalte in der gridview-von-relation und die Sortierung in gridview

Sie haben, fügen Sie einfach $query->orderBy('lib_cities.city_name ASC');
dies funktioniert aber wenn ich auf einen anderen header, Er sortiert immer von lib_cities...
ok. Ich versuche deinen code.

InformationsquelleAutor beginner | 2015-04-09

Schreibe einen Kommentar