YII First Example
After installing Yii, you can develop an application that can be accessed via URL http://hostname/basic/web/index.php or http://hostname/index.php depending upon your configuration.
We'll run a basic example of Hello World on Yii2.
Step1 Declaring action in controllers
We are creating an action called example. This action will read a message parameter from the request and will display that message.
Action is always declared in the Controllers file. Here, we are not creating a new file and is declaring this action in the existing SiteController.php.
Following is the starting code in SiteController.php file.
- <?php
- namespace frontend\controllers;
-
- use Yii;
- use yii\base\InvalidParamException;
- use yii\web\BadRequestHttpException;
- use yii\web\Controller;
- use yii\filters\VerbFilter;
- use yii\filters\AccessControl;
- use common\models\LoginForm;
- use frontend\models\PasswordResetRequestForm;
- use frontend\models\ResetPasswordForm;
- use frontend\models\SignupForm;
- use frontend\models\ContactForm;
-
-
-
-
- class SiteController extends Controller
- {
-
-
-
-
- public function actionExample($message = 'Hello')
- {
- return $this->render('example', ['message' => $message]);
- }
Look at the above code, example action is defined as a method named actionExample. Prefix action is used to differentiate action methods from non-action methods. Name after the prefix action denotes the action's ID.
Here we're taking a parameter $message, whose value is "Hello". If a request is sent with a message parameter in the URL with a different value say "Hyii", then this value will be displayed in the output. If no message parameter request is made in the URL, then "Hello" will be printed.
Function render() is called to display view file named example.php. This result will be displayed to the end user in the browser.
Step1 Creating View file
View folder basically contains the response content which will be delivered to the user on their request. In this example, we have created a file named example.php in the view/site folder.
Following is the code of example.php file.
- <?php
- use yii\helpers\Html;
- ?>
- <?= Html::encode($message) ?>
Look at the above code, the message parameter is HTML encoded before being printed to prevent from XSS attack.
Step1 Running on Browser
Access the page with the following URL:
http://localhost/hello/frontend/web/index.php?r=site%2Fexample&message=Hello+World
output is shown below.
Look at the above snapshot, output displays Hello World. In the URL, we have requested for message parameter.
If we'll omit the message parameter in the URL, then our URL will be:
http://localhost/hello/frontend/web/index.php?r=site%2Fexample
and our Output will be only "Hello".
In the URL, we have mentioned an r parameter. This r denotes to route. It's format is ControllerID/AtionID. In this example route denotes site/example.
What is Gii
Gii is an automatic code generation tool introduced in Yii 2.0. Code generation in Gii is quiet easy as filling the right information as per the instructions.
Starting Gii
By default, Gii is always enabled in the developing mode due to following code in the entry script web/index.php file in Yii:
defined('YII_ENV') or define('YII_ENV', 'dev');
http://localhost/advanced2/frontend/web/index.php?r=gii
This is the Gii output. From here you can generate your codes automatically.
Yii CRUD
Yii provides a gii tool which is a code generator tool. It gives you the generated code for CRUD. We'll learn how to generate CRUD with gii.
A simple example is shown here to generate a crud. We have named the Yii2 folder as crud. And our table name is employees.
Step 1 Open Gii
In the browser, type the following, http://localhost/crud/frontend/web/index.php?r=gii
Step 2 Generate Model
Look at the above snapshot, enter the table name which is employees in our case. Employees model class will be generated. Scroll down the page and click on Preview button.
Look at the above snpashot, click on Generate button to generate the code.
You'll see a successfull message as shown above.
Step 2 Generate CRUD
Look at the above snapshot,
In Model class, file Employees with the path frontend\models\Employees is generated.
In Search Model class, file EmployeesSearch with the path frontend\controllers\EmployeesSearch is generated.
In Controller class, file EmployeesController with the path @frontend\views\Employees is generated.
Click on Preview button to check for error. If no error is there, click on Generate button to generaate the code. Again you'll get a succesfull message for code generation.
Now our CRUD has been succesfully generated. To check it, run it on browser with the URL http://localhost/crud/frontend/web/index.php?r=employees/
Look at the above snapshot, Employees is our table name and you can search an entry from this table.
To insert values in the table click on Create Employees button. Following page will appear.
Fill the details above, and click on Create button. Data will be inserted in the table employees.
Look at the above snapshot, we have filled some entries in the table. Here you can see the icons to View, Update and Delete.
On clicking View icon, following page containing John's information will appear.
On clicking Update icon, following page containing John's information will appear where you can edit anything. Click on Update button after making changes.
On clicking Delete icon, following box will appear asking you to delete it or not.
Generated Code
In controllers, file EmployeesController.php will have the following code.
- <?php
-
- namespace frontend\controllers;
-
- use Yii;
- use frontend\models\Employees;
- use frontend\models\EmployeesSearch;
- use yii\web\Controller;
- use yii\web\NotFoundHttpException;
- use yii\filters\VerbFilter;
-
-
-
-
- class EmployeesController extends Controller
- {
-
-
-
- public function behaviors()
- {
- return [
- 'verbs' => [
- 'class' => VerbFilter::className(),
- 'actions' => [
- 'delete' => ['POST'],
- ],
- ],
- ];
- }
-
-
-
-
-
- public function actionIndex()
- {
- $searchModel = new EmployeesSearch();
- $dataProvider = $searchModel->search(Yii::$app->request->queryParams);
-
- return $this->render('index', [
- 'searchModel' => $searchModel,
- 'dataProvider' => $dataProvider,
- ]);
- }
-
-
-
-
-
-
- public function actionView($id)
- {
- return $this->render('view', [
- 'model' => $this->findModel($id),
- ]);
- }
-
-
-
-
-
-
- public function actionCreate()
- {
- $model = new Employees();
-
- if ($model->load(Yii::$app->request->post()) && $model->save()) {
- return $this->redirect(['view', 'id' => $model->id]);
- } else {
- return $this->render('create', [
- 'model' => $model,
- ]);
- }
- }
-
-
-
-
-
-
-
- public function actionUpdate($id)
- {
- $model = $this->findModel($id);
-
- if ($model->load(Yii::$app->request->post()) && $model->save()) {
- return $this->redirect(['view', 'id' => $model->id]);
- } else {
- return $this->render('update', [
- 'model' => $model,
- ]);
- }
- }
-
-
-
-
-
-
-
- public function actionDelete($id)
- {
- $this->findModel($id)->delete();
- return $this->redirect(['index']);
- }
-
-
-
-
-
-
-
-
- protected function findModel($id)
- {
- if (($model = Employees::findOne($id)) !== null) {
- return $model;
- } else {
- throw new NotFoundHttpException('The requested page does not exist.');
- }
- }
- }
In models, file Employees.php will have the following code.
- <?php
-
- namespace frontend\models;
-
- use Yii;
-
-
-
-
-
-
-
-
-
-
- class Employees extends \yii\db\ActiveRecord
- {
-
-
-
- public static function tableName()
- {
- return 'employees';
- }
-
-
-
-
- public function rules()
- {
- return [
- [['name', 'designation', 'contact', 'email'], 'required'],
- [['contact'], 'integer'],
- [['name'], 'string', 'max' => 20],
- [['designation'], 'string', 'max' => 50],
- [['email'], 'string', 'max' => 80],
- ];
- }
-
-
-
-
- public function attributeLabels()
- {
- return [
- 'id' => 'ID',
- 'name' => 'Name',
- 'designation' => 'Designation',
- 'contact' => 'Contact',
- 'email' => 'Email',
- ];
- }
- }
In models, file EmployeesSearch.php will have the following code.
- <?php
-
- namespace frontend\models;
-
- use Yii;
- use yii\base\Model;
- use yii\data\ActiveDataProvider;
- use frontend\models\Employees;
-
-
-
-
- class EmployeesSearch extends Employees
- {
-
-
-
- public function rules()
- {
- return [
- [['id', 'contact'], 'integer'],
- [['name', 'designation', 'email'], 'safe'],
- ];
- }
-
-
-
-
- public function scenarios()
- {
-
- return Model::scenarios();
- }
-
-
-
-
-
-
-
-
- public function search($params)
- {
- $query = Employees::find();
-
-
-
- $dataProvider = new ActiveDataProvider([
- 'query' => $query,
- ]);
-
- $this->load($params);
-
- if (!$this->validate()) {
-
- records when validation fails
-
- return $dataProvider;
- }
-
-
- $query->andFilterWhere([
- 'id' => $this->id,
- 'contact' => $this->contact,
- ]);
-
- $query->andFilterWhere(['like', 'name', $this->name])
- ->andFilterWhere(['like', 'designation', $this->designation])
- ->andFilterWhere(['like', 'email', $this->email]);
-
- return $dataProvider;
- }
- }
In views, file view.php will have the following code.
- <?php
-
- use yii\helpers\Html;
- use yii\widgets\DetailView;
-
-
-
-
- $this->title = $model->name;
- $this->params['breadcrumbs'][] = ['label' => 'Employees', 'url' => ['index']];
- $this->params['breadcrumbs'][] = $this->title;
- ?>
- <div class="employees-view">
-
- <h1><?= Html::encode($this->title) ?></h1>
-
- <p>
- <?= Html::a('Update', ['update', 'id' => $model->id], ['class' => 'btn btn-primary']) ?>
- <?= Html::a('Delete', ['delete', 'id' => $model->id], [
- 'class' => 'btn btn-danger',
- 'data' => [
- 'confirm' => 'Are you sure you want to delete this item?',
- 'method' => 'post',
- ],
- ]) ?>
- </p>
-
- <?= DetailView::widget([
- 'model' => $model,
- 'attributes' => [
- 'id',
- 'name',
- 'designation',
- 'contact',
- 'email:email',
- ],
- ]) ?>
-
- </div>
In views, file form.php will have the following code.
- <?php
-
- use yii\helpers\Html;
- use yii\widgets\ActiveForm;
-
-
-
-
- ?>
-
- <div class="employees-form">
-
- <?php $form = ActiveForm::begin(); ?>
-
- <?= $form->field($model, 'name')->textInput(['maxlength' => true]) ?>
-
- <?= $form->field($model, 'designation')->textInput(['maxlength' => true]) ?>
-
- <?= $form->field($model, 'contact')->textInput() ?>
-
- <?= $form->field($model, 'email')->textInput(['maxlength' => true]) ?>
-
- <div class="form-group">
- <?= Html::submitButton($model->isNewRecord ? 'Create' : 'Update', ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>
- </div>
-
- <?php ActiveForm::end(); ?>
-
- </div>
In views, file search.php will have the following code.
- <?php
-
- use yii\helpers\Html;
- use yii\widgets\ActiveForm;
-
-
-
-
- ?>
-
- <div class="employees-search">
-
- <?php $form = ActiveForm::begin([
- 'action' => ['index'],
- 'method' => 'get',
- ]); ?>
-
- <?= $form->field($model, 'id') ?>
-
- <?= $form->field($model, 'name') ?>
-
- <?= $form->field($model, 'designation') ?>
-
- <?= $form->field($model, 'contact') ?>
-
- <?= $form->field($model, 'email') ?>
-
- <div class="form-group">
- <?= Html::submitButton('Search', ['class' => 'btn btn-primary']) ?>
- <?= Html::resetButton('Reset', ['class' => 'btn btn-default']) ?>
- </div>
-
- <?php ActiveForm::end(); ?>
-
- </div>
In views, file create.php will have the following code.
- <?php
-
- use yii\helpers\Html;
-
-
-
-
-
- $this->title = 'Create Employees';
- $this->params['breadcrumbs'][] = ['label' => 'Employees', 'url' => ['index']];
- $this->params['breadcrumbs'][] = $this->title;
- ?>
- <div class="employees-create">
-
- <h1><?= Html::encode($this->title) ?></h1>
-
- <?= $this->render('_form', [
- 'model' => $model,
- ]) ?>
-
- </div>
In views, file index.php will have the following code.
- <?php
-
- use yii\helpers\Html;
- use yii\grid\GridView;
-
-
-
-
-
- $this->title = 'Employees';
- $this->params['breadcrumbs'][] = $this->title;
- ?>
- <div class="employees-index">
-
- <h1><?= Html::encode($this->title) ?></h1>
- <?php
-
- <p>
- <?= Html::a('Create Employees', ['create'], ['class' => 'btn btn-success']) ?>
- </p>
- <?= GridView::widget([
- 'dataProvider' => $dataProvider,
- 'filterModel' => $searchModel,
- 'columns' => [
- ['class' => 'yii\grid\SerialColumn'],
-
- 'id',
- 'name',
- 'designation',
- 'contact',
- 'email:email',
-
- ['class' => 'yii\grid\ActionColumn'],
- ],
- ]); ?>
- </div>
In views, file update.php will have the following code.
- <?php
-
- use yii\helpers\Html;
-
-
-
-
- $this->title = 'Update Employees: ' . $model->name;
- $this->params['breadcrumbs'][] = ['label' => 'Employees', 'url' => ['index']];
- $this->params['breadcrumbs'][] = ['label' => $model->name, 'url' => ['view', 'id' => $model->id]];
- $this->params['breadcrumbs'][] = 'Update';
- ?>
- <div class="employees-update">
-
- <h1><?= Html::encode($this->title) ?></h1>
-
- <?= $this->render('_form', [
- 'model' => $model,
- ]) ?>
-
- </div>
No comments:
Post a Comment