Yii - Sắp xếp

Khi hiển thị nhiều dữ liệu, chúng ta thường cần sắp xếp dữ liệu. Yii sử dụng mộtyii\data\Sort object để biểu diễn một lược đồ sắp xếp.

Để hiển thị sắp xếp trong hành động, chúng tôi cần dữ liệu.

Chuẩn bị DB

Step 1- Tạo cơ sở dữ liệu mới. Cơ sở dữ liệu có thể được chuẩn bị theo hai cách sau.

  • In the terminal run mysql -u root –p

  • Create a new database via CREATE DATABASE helloworld CHARACTER SET utf8 COLLATE utf8_general_ci;

Step 2 − Configure the database connection in the config/db.php file. The following configuration is for the system used currently.

<?php
   return [
      'class' => 'yii\db\Connection',
      'dsn' => 'mysql:host=localhost;dbname=helloworld',
      'username' => 'vladimir',
      'password' => '12345',
      'charset' => 'utf8',
   ];
?>

Step 3 − Inside the root folder run ./yii migrate/create test_table. This command will create a database migration for managing our DB. The migration file should appear in the migrations folder of the project root.

Step 4 − Modify the migration file (m160106_163154_test_table.php in this case) this way.

<?php
   use yii\db\Schema;
   use yii\db\Migration;
   class m160106_163154_test_table extends Migration {
      public function safeUp() {
         $this->createTable("user", [ "id" => Schema::TYPE_PK, "name" => Schema::TYPE_STRING, "email" => Schema::TYPE_STRING, ]); $this->batchInsert("user", ["name", "email"], [
            ["User1", "[email protected]"],
            ["User2", "[email protected]"],
            ["User3", "[email protected]"],
            ["User4", "[email protected]"],
            ["User5", "[email protected]"],
            ["User6", "[email protected]"],
            ["User7", "[email protected]"],
            ["User8", "[email protected]"],
            ["User9", "[email protected]"],
            ["User10", "[email protected]"],
            ["User11", "[email protected]"],
         ]);
      }
      public function safeDown() {
         $this->dropTable('user');
      }
   }
?>

The above migration creates a user table with these fields: id, name, and email. It also adds a few demo users.

Step 5 − Inside the project root run ./yii migrate to apply the migration to the database.

Step 6 − Now, we need to create a model for our user table. For the sake of simplicity, we are going to use the Gii code generation tool. Open up this url: http://localhost:8080/index.php?r=gii. Then, click the “Start” button under the “Model generator” header. Fill in the Table Name (“user”) and the Model Class(“MyUser”), click the “Preview” button and finally, click the “Generate” button.

The MyUser model should appear in the models directory.

Sorting in Action

Step 1 − Add an actionSorting method to the SiteController.

public function actionSorting() {
   //declaring the sort object
   $sort = new Sort([
      'attributes' => ['id', 'name', 'email'], 
   ]);
   //retrieving all users
   $models = MyUser::find() ->orderBy($sort->orders)
      ->all();
   return $this->render('sorting', [ 'models' => $models,
      'sort' => $sort,
   ]);
}

Step 2 − Create a View file called sorting inside the views/site folder.

<?php
   // display links leading to sort actions
   echo $sort->link('id') . ' | ' . $sort->link('name') . ' | ' . $sort->link('email');
?><br/>
<?php foreach ($models as $model): ?>
   <?= $model->id; ?> <?= $model->name; ?>
   <?= $model->email; ?>
   <br/>
<?php endforeach; ?>

Step 3 − Now, if you type http://localhost:8080/index.php?r=site/sorting in the web browser, you can see that the id, name, and email fields is sortable as shown in the following image.