Yii – GridView Widget ”; Previous Next The GridView widget takes data from a data provider and presents data in the form of a table. Each row of the table represents a single data item, and a column represents an attribute of the item. Step 1 − Modify the datawidget view this way. <?php use yiigridGridView; echo GridView::widget([ ”dataProvider” => $dataProvider, ]); ?> Step 2 − Go to http://localhost:8080/index.php?r=site/data-widget, you will see a typical usage of the DataGrid widget. The columns of the DataGrid widget are configured in terms of the yiigridColumn class. It represents a model attribute and can be filtered and sorted. Step 3 − To add a custom column to the grid, modify the datawidget view this way. <?php yiigridGridView; echo GridView::widget([ ”dataProvider” => $dataProvider, ”columns” => [ ”id”, [ ”class” => ”yiigridDataColumn”, // can be omitted, as it is the default ”label” => ”Name and email”, ”value” => function ($data) { return $data->name . ” writes from ” . $data->email; }, ], ], ]); ?> Step 4 − If you go to the address http://localhost:8080/index.php?r=site/data-widget, you will see the output as shown in the following image. Grid columns can be customized by using different column classes, like yiigridSerialColumn, yiigridActionColumn, and yiigridCheckboxColumn. Step 5 − Modify the datawidget view in the following way. <?php use yiigridGridView; echo GridView::widget([ ”dataProvider” => $dataProvider, ”columns” => [ [”class” => ”yiigridSerialColumn”], ”name”, [”class” => ”yiigridActionColumn”], [”class” => ”yiigridCheckboxColumn”], ], ]); ?> Step 6 −Go to http://localhost:8080/index.php?r=site/data-widget, you will see the following. Print Page Previous Next Advertisements ”;
Category: yii
Yii – Data Providers
Yii – Data Providers ”; Previous Next Yii provides a set of data provider classes that encapsulate pagination and sorting. A data provider implements yiidataDataProviderInterface. It supports retrieving sorted and paginated data. Data providers usually work with data widgets. Yii includes − ActiveDataProvider − Uses yiidbActiveQuery or yiidbQuery to query data from databases. SqlDataProvider − Executes SQL and returns data as arrays. ArrayDataProvider − Takes a big array and returns a slice of it. You define the sorting and pagination behaviors of a data-provider by configuring its pagination and sort properties. Data widgets, such as yiigridGridView, have a property called dataProvider, which takes a data provider instance and displays the data on the screen. Preparing the DB Step 1 − Create a new database. Database can be prepared in the following two ways. 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” => ”yiidbConnection”, ”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 yiidbSchema; use yiidbMigration; 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. Active Data Provider Step 1 − Create a function called actionDataProvider inside the SiteController. public function actionDataProvider(){ $query = MyUser::find(); $provider = new ActiveDataProvider([ ”query” => $query, ”pagination” => [ ”pageSize” => 2, ], ]); // returns an array of users objects $users = $provider->getModels(); var_dump($users); } In the code above, we define an instance of the ActiveDataProvider class and display users from the first page. The yiidataActiveDataProvider class uses the DB application component as the DB connection. Step 2 − If you enter the local host address http://localhost:8080/index.php?r=site/dataprovider, you will see the following output. SQL Data Provider The yiidataSqlDataProvider class works with raw SQL statements. Step 1 − Modify the actionDataProvider method this way. public function actionDataProvider() { $count = Yii::$app->db->createCommand(”SELECT COUNT(*) FROM user”)->queryScalar(); $provider = new SqlDataProvider([ ”sql” => ”SELECT * FROM user”, ”totalCount” => $count, ”pagination” => [ ”pageSize” => 5, ], ”sort” => [ ”attributes” => [ ”id”, ”name”, ”email”, ], ], ]); // returns an array of data rows $users = $provider->getModels(); var_dump($users); } Step 2 − Type http://localhost:8080/index.php?r=site/data-provider in the address bar of the web browser, you will see the following output. Array Data Provider The yiidataArrayDataProvider class is best for working with big arrays. Elements in this array can be either query results of DAO or Active Record instances. Step 1 − Modify the actionDataProvider method this way. public function actionDataProvider() { $data = MyUser::find()->asArray()->all(); $provider = new ArrayDataProvider([ ”allModels” => $data, ”pagination” => [ ”pageSize” => 3, ], ”sort” => [ ”attributes” => [”id”, ”name”], ], ]); // get the rows in the currently requested page $users = $provider->getModels(); var_dump($users); } Step 2 − If you go to the address http://localhost:8080/index.php?r=site/data-provider through the web browser, you will see the following output. Notice, that unlike SQL Data Provider and Active Data Provider, Array Data Provider loads all data into the memory, so it is less efficient. Print Page Previous Next Advertisements ”;
Yii – Creating Event
Yii – Creating Event ”; Previous Next In this chapter we will see to create an event in Yii. To show events in action, we need data. Preparing the DB Step 1 − Create a new database. Database can be prepared in the following two ways. 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” => ”yiidbConnection”, ”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 yiidbSchema; use yiidbMigration; 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. Create an Event Assume we want to send an email to the admin whenever a new user registers on our web site. Step 1 − Modify the models/MyUser.php file this way. <?php namespace appmodels; use Yii; /** * This is the model class for table “user”. * * @property integer $id * @property string $name * @property string $email */ class MyUser extends yiidbActiveRecord { const EVENT_NEW_USER = ”new-user”; public function init() { // first parameter is the name of the event and second is the handler. $this->on(self::EVENT_NEW_USER, [$this, ”sendMailToAdmin”]); } /** * @inheritdoc */ public static function tableName() { return ”user”; } /** * @inheritdoc */ public function rules() { return [ [[”name”, ”email”], ”string”, ”max” => 255] ]; } /** * @inheritdoc */ public function attributeLabels() { return [ ”id” => ”ID”, ”name” => ”Name”, ”email” => ”Email”, ]; } public function sendMailToAdmin($event) { echo ”mail sent to admin using the event”; } } ?> In the above code, we define a “new-user” event. Then, in the init() method we attach the sendMailToAdmin function to the “new-user” event. Now, we need to trigger this event. Step 2 − Create a method called actionTestEvent in the SiteController. public function actionTestEvent() { $model = new MyUser(); $model->name = “John”; $model->email = “[email protected]”; if($model->save()) { $model->trigger(MyUser::EVENT_NEW_USER); } } In the above code, we create a new user and trigger the “new-user” event. Step 3 − Now type http://localhost:8080/index.php?r=site/test-event, you will see the following. Print Page Previous Next Advertisements ”;
Yii – Files Upload
Yii – Files Upload ”; Previous Next You can easily implement a file uploading function with the help of yiiwebUploadedFile, models and yiiwidgetsActiveForm. Create a directory ‘uploads’ in the root folder. This directory will hold all of the uploaded images. To upload a single file, you need to create a model and an attribute of the model for uploaded file instance. You should also validate the file upload. Step 1 − Inside the models folder, create a file called UploadImageForm.php with the following content. <?php namespace appmodels; use yiibaseModel; class UploadImageForm extends Model { public $image; public function rules() { return [ [[”image”], ”file”, ”skipOnEmpty” => false, ”extensions” => ”jpg, png”], ]; } public function upload() { if ($this->validate()) { $this->image->saveAs(”../uploads/” . $this->image->baseName . ”.” . $this->image->extension); return true; } else { return false; } } } ?> The image attribute is used to keep the file instance. The file validation rule ensures that a file has a png or a jpg extension. The upload function validates the file and saves it on the server. Step 2 − Now, add the actionUploadImage function to the SiteController. public function actionUploadImage() { $model = new UploadImageForm(); if (Yii::$app->request->isPost) { $model->image = UploadedFile::getInstance($model, ”image”); if ($model->upload()) { // file is uploaded successfully echo “File successfully uploaded”; return; } } return $this->render(”upload”, [”model” => $model]); } Step 3 − When the form is submitted, we call the yiiwebUploadedFile::getInstance() function to represent the uploaded file as an UploadedFile instance. Then, we validate the file and save it on the server. Step 4 − Next, create an upload.php view file inside the views/site directory. <?php use yiiwidgetsActiveForm; ?> <?php $form = ActiveForm::begin([”options” => [”enctype” => ”multipart/form-data”]])?> <?= $form->field($model, ”image”)->fileInput() ?> <button>Submit</button> <?php ActiveForm::end() ?> Remember to add the enctype option when you upload a file. The fileInput() method renders the following html code − <input type = “file”> The above html code allows the users to select and upload files. Step 5 − Now, if you go to http://localhost:8080/index.php?r=site/upload-image, you will see the following. Step 6 − Select an image to upload and click the “submit” button. The file will be saved on the server inside the ‘uploads’ folder. Print Page Previous Next Advertisements ”;
Gii – Generating Module
Gii – Generating Module ”; Previous Next Let us see how to generate a Module. Step 1 − To generate a module, open the module generation interface and fill in the form. Step 2 − Then, click the “Preview” button and “Generate”. Step 3 − We need to activate the module. Modify the modules application component in the config/web.php file. ”modules” => [ ”admin” => [ ”class” => ”appmodulesadminModule”, ], ], Step 4 − To check whether our newly generated module works, type the UR http://localhost:8080/index.php?r=admin/default/index in the web browser. Print Page Previous Next Advertisements ”;
Gii – Generating Controller
Gii – Generating Controller ”; Previous Next Let us see how to generate a Controller. Step 1 − To generate a controller with several actions, open the controller generator interface fill in the form. Step 2 − Then, click the “Preview” button and “Generate”. The CustomController.php file with index, hello, and world actions will be generated in the controllers folder. <?php namespace appcontrollers; class CustomController extends yiiwebController { public function actionHello() { return $this->render(”hello”); } public function actionIndex() { return $this->render(”index”); } public function actionWorld() { return $this->render(”world”); } } ?> Form Generation Step 1 − To generate a view file from an existing model, open the form generation interface and fill in the form. Then, click the “Preview” button and “Generate”. The customview view file will be generated in the view folder. Step 2 − To display it, add a new method to the CustomController. public function actionView() { $model = new MyUser(); return $this->render(”/customview”, [ ”model” => $model, ]); } Step 3 − To see the generated view file, open the URL http://localhost:8080/index.php?r=custom/view. Print Page Previous Next Advertisements ”;
Yii – Using Cookies
Yii – Using Cookies ”; Previous Next Cookies allow data to be persisted across requests. In PHP, you may access them through the $_COOKIE variable. Yii represents cookie as an object of the yiiwebCookie class. In this chapter, we describe several methods for reading cookies. Step 1 − Create an actionReadCookies method in the SiteController. public function actionReadCookies() { // get cookies from the “request” component $cookies = Yii::$app->request->cookies; // get the “language” cookie value // if the cookie does not exist, return “ru” as the default value $language = $cookies->getValue(”language”, ”ru”); // an alternative way of getting the “language” cookie value if (($cookie = $cookies->get(”language”)) !== null) { $language = $cookie->value; } // you may also use $cookies like an array if (isset($cookies[”language”])) { $language = $cookies[”language”]->value; } // check if there is a “language” cookie if ($cookies->has(”language”)) echo “Current language: $language”; } Step 2 − To see sending cookies in action, create a method called actionSendCookies in the SiteController. public function actionSendCookies() { // get cookies from the “response” component $cookies = Yii::$app->response->cookies; // add a new cookie to the response to be sent $cookies->add(new yiiwebCookie([ ”name” => ”language”, ”value” => ”ru-RU”, ])); $cookies->add(new yiiwebCookie([ ”name” => ”username”, ”value” => ”John”, ])); $cookies->add(new yiiwebCookie([ ”name” => ”country”, ”value” => ”USA”, ])); } Step 3 − Now, if you go to http://localhost:8080/index.php?r=site/send-cookies, you will notice that cookies are saved inside the browser. In Yii, by default, cookie validation is enabled. It protects the cookies from being modified on the client side. The hash string from the config/web.php file signs each cookie. <?php $params = require(__DIR__ . ”/params.php”); $config = [ ”id” => ”basic”, ”basePath” => dirname(__DIR__), ”bootstrap” => [”log”], ”components” => [ ”request” => [ // !!! insert a secret key in the following (if it is empty) – this is //required by cookie validation ”cookieValidationKey” => ”ymoaYrebZHa8gURuolioHGlK8fLXCKjO”, ], ”cache” => [ ”class” => ”yiicachingFileCache”, ], ”user” => [ ”identityClass” => ”appmodelsUser”, ”enableAutoLogin” => true, ], ”errorHandler” => [ ”errorAction” => ”site/error”, ], ”mailer” => [ ”class” => ”yiiswiftmailerMailer”, // send all mails to a file by default. You have to set // ”useFileTransport” to false and configure a transport // for the mailer to send real emails. ”useFileTransport” => true, ], ”log” => [ ”traceLevel” => YII_DEBUG ? 3 : 0, ”targets” => [ [ ”class” => ”yiilogFileTarget”, ”levels” => [”error”, ”warning”], ], ], ], ”urlManager” => [ //”showScriptName” => false, //”enablePrettyUrl” => true, //”enableStrictParsing” => true, //”suffix” => ”/” ], ”db” => require(__DIR__ . ”/db.php”), ], ”modules” => [ ”hello” => [ ”class” => ”appmoduleshelloHello”, ], ], ”params” => $params, ]; if (YII_ENV_DEV) { // configuration adjustments for ”dev” environment $config[”bootstrap”][] = ”debug”; $config[”modules”][”debug”] = [ ”class” => ”yiidebugModule”, ]; $config[”bootstrap”][] = ”gii”; $config[”modules”][”gii”] = [ ”class” => ”yiigiiModule”, ]; } return $config; ?> You can disable cookie validation by setting the yiiwebRequest::$enableCookieValidation property to false. Print Page Previous Next Advertisements ”;
Yii – Validation
Yii – Validation ”; Previous Next You should never trust the data received from users. To validate a model with user inputs, you should call yiibaseModel::validate() method. It returns a Boolean value if the validation succeeds. If there are errors, you may get them from the yiibaseModel::$errors property. Using Rules To make the validate() function work, you should override the yiibaseModel::rules() method. Step 1 − The rules() method returns an array in the following format. [ // required, specifies which attributes should be validated [”attr1”, ”attr2”, …], // required, specifies the type a rule. ”type_of_rule”, // optional, defines in which scenario(s) this rule should be applied ”on” => [”scenario1”, ”scenario2”, …], // optional, defines additional configurations ”property” => ”value”, … ] For each rule, you should define at least which attributes the rule applies to and the type of rule applied. The core validation rules are − boolean, captcha, compare, date, default, double, each, email, exist, file, filter, image, ip, in, integer, match, number, required, safe, string, trim, unique, url. Step 2 − Create a new model in the models folder. <?php namespace appmodels; use Yii; use yiibaseModel; class RegistrationForm extends Model { public $username; public $password; public $email; public $country; public $city; public $phone; public function rules() { return [ // the username, password, email, country, city, and phone attributes are //required [[”username” ,”password”, ”email”, ”country”, ”city”, ”phone”], ”required”], // the email attribute should be a valid email address [”email”, ”email”], ]; } } ?> We have declared the model for the registration form. The model has five properties − username, password, email, country, city, and phone. They are all required and the email property must be a valid email address. Step 3 − Add the actionRegistration method to the SiteController where we create a new RegistrationForm model and pass it to a view. public function actionRegistration() { $model = new RegistrationForm(); return $this->render(”registration”, [”model” => $model]); } Step 4 − Add a view for our registration form. Inside the views/site folder, create a file called registration.php with the following code. <?php use yiibootstrapActiveForm; use yiibootstrapHtml; ?> <div class = “row”> <div class = “col-lg-5″> <?php $form = ActiveForm::begin([”id” => ”registration-form”]); ?> <?= $form->field($model, ”username”) ?> <?= $form->field($model, ”password”)->passwordInput() ?> <?= $form->field($model, ”email”)->input(”email”) ?> <?= $form->field($model, ”country”) ?> <?= $form->field($model, ”city”) ?> <?= $form->field($model, ”phone”) ?> <div class = “form-group”> <?= Html::submitButton(”Submit”, [”class” => ”btn btn-primary”, ”name” => ”registration-button”]) ?> </div> <?php ActiveForm::end(); ?> </div> </div> We are using the ActiveForm widget for displaying our registration form. Step 5 − If you go to the local host http://localhost:8080/index.php?r=site/registration and click the submit button, you will see validation rules in action. Step 6 − To customize the error message for the username property, modify the rules() method of the RegistrationForm in the following way. public function rules() { return [ // the username, password, email, country, city, and phone attributes are required [[”password”, ”email”, ”country”, ”city”, ”phone”], ”required”], [”username”, ”required”, ”message” => ”Username is required”], // the email attribute should be a valid email address [”email”, ”email”], ]; } Step 7 − Go to the local host http://localhost:8080/index.php?r=site/registration and click the submit button. You will notice that the error message of the username property has changed. Step 8 − To customize the validation process, you may override these methods. yiibaseModel::beforeValidate(): triggers a yiibaseModel::EVENT_BEFORE_VALIDATE event. yiibaseModel::afterValidate(): triggers a yiibaseModel::EVENT_AFTER_VALIDATE event. Step 9 − To trim the spaces around the country property and turn empty input of the city property into a null, you may the trim and default validators. public function rules() { return [ // the username, password, email, country, city, and phone attributes are required [[”password”, ”email”, ”country”, ”city”, ”phone”], ”required”], [”username”, ”required”, ”message” => ”Username is required”], [”country”, ”trim”], [”city”, ”default”], // the email attribute should be a valid email address [”email”, ”email”], ]; } Step 10 − If an input is empty, you can set a default value for it. public function rules() { return [ [”city”, ”default”, ”value” => ”Paris”], ]; } If the city property is empty, then the default “Paris” value will be used. Print Page Previous Next Advertisements ”;
Yii – Sessions
Yii – Sessions ”; Previous Next Sessions make data accessible across various pages. A session creates a file on the server in a temporary directory where all session variables are stored. This data is available to all the pages of your web site during the visit of that particular user. When a session starts, the following happens − PHP creates a unique ID for that particular session. A cookie called PHPSESSID is sent on the client side (to the browser). The server creates a file in the temporary folder where all session variables are saved. When a server wants to retrieve the value from a session variable, PHP automatically gets the unique session ID from the PHPSESSID cookie. Then, it looks in its temporary directory for the needed file. To start a session, you should call the session_start() function. All session variables are stored in the $_SESSION global variable. You can also use the isset() function to check whether the session variable is set − <?php session_start(); if( isset( $_SESSION[”number”] ) ) { $_SESSION[”number”] += 1; }else { $_SESSION[”number”] = 1; } $msg = “This page was visited “. $_SESSION[”number”]; $msg .= “in this session.”; echo $msg; ?> To destroy a session, you should call the session_destroy() function. To destroy a single session variable, call the unset() function − <?php unset($_SESSION[”number”]); session_destroy(); ?> Using Sessions in Yii Sessions allow data to be persisted across user requests. In PHP, you may access them through the $_SESSION variable. In Yii, you can get access to sessions via the session application component. Step 1 − Add the actionOpenAndCloseSession method to the SiteController. public function actionOpenAndCloseSession() { $session = Yii::$app->session; // open a session $session->open(); // check if a session is already opened if ($session->isActive) echo “session is active”; // close a session $session->close(); // destroys all data registered to a session $session->destroy(); } In the above code, we get the session application component, open a session, check whether it is active, close the session, and finally destroy it. Step 2 − Type http://localhost:8080/index.php?r=site/open-and-close-session in the address bar of the web browser, you will see the following. To access session variables, you may use set() and get() methods. Step 3 − Add an actionAccessSession method to the SiteController. public function actionAccessSession() { $session = Yii::$app->session; // set a session variable $session->set(”language”, ”ru-RU”); // get a session variable $language = $session->get(”language”); var_dump($language); // remove a session variable $session->remove(”language”); // check if a session variable exists if (!$session->has(”language”)) echo “language is not set”; $session[”captcha”] = [ ”value” => ”aSBS23”, ”lifetime” => 7200, ]; var_dump($session[”captcha”]); } Step 4 − Go to http://localhost:8080/index.php?r=site/access-session, you will see the following. Print Page Previous Next Advertisements ”;
Yii – Gii
Yii – Gii ”; Previous Next Gii is the extension, that provides a web-based code generator for generating models, forms, modules, CRUD, and so forth. By default, the following generators are available − Model Generator − Generates an ActiveRecord class for the specified database table. CRUD Generator − Generates a controller and views that implement CRUD (Create, Read, Update, Delete) operations for the specified model. Controller Generator − Generates a new controller class with one or several controller actions and their corresponding views. Form Generator − Generates a view script file that displays a form to collect input for the specified model class. Module Generator − Generates the skeleton code needed by an Yii module. Extension Generator − GenerateS the files needed by a Yii extension. To open the gii generation tool, type http://localhost:8080/index.php?r=gii: in the address bar of the web browser. Preparing the DB Step 1 − Create a new database. Database can be prepared in the following two ways − 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” => ”yiidbConnection”, ”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 yiidbSchema; use yiidbMigration; 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. Print Page Previous Next Advertisements ”;