Now we'll fetch the data from our table child. Here our Yiii2 folder is named as read.
Step 1 Create Model file
Create a model file child.php in frontend/models folder.
- <?php
- namespace app\models;
-
- use Yii;
-
- class Child extends \yii\db\ActiveRecord
- {
-
-
-
- public static function tableName()
- {
- return 'child';
- }
-
-
-
-
- public function rules()
- {
- return [
- [['name', 'meaning', 'gender'], 'required'],
- [['name', 'meaning'], 'string', 'max' => 100],
- [['gender'], 'string', 'max' => 15]
- ];
- }
- }
Step 2 Add action to read
In the ChildController.php file, we need to add the action actionIndex to fetch the data from the table.
- <?php
- namespace frontend\controllers;
-
- use Yii;
- use app\models\Child;
- use yii\web\Controller;
-
-
-
-
-
- class ChildController extends Controller
- {
-
-
-
- public function actionCreate()
- {
-
- $model = new Child();
-
-
- if($model->load(Yii::$app->request->post()) && $model->save()){
- return $this->redirect(['index']);
- }
-
- return $this->render('create', ['model' => $model]);
- }
-
-
-
-
- public function actionIndex()
- {
- $child = Child::find()->all();
-
- return $this->render('index', ['model' => $child]);
- }
- }
Look at the above code, all code is same only action to fetch data is added in the last.
Step 3 Create View file
In the frontend/views/child folder, create a file index.php.
- <?php
- use yii\helpers\Html;
- ?>
-
- <style>
- table th,td{
- padding: 10px;
- }
- </style>
-
- <?= Html::a('Create', ['child/create'], ['class' => 'btn btn-success']); ?>
-
- <table border="1">
- <tr>
- <th>Name</th>
- <th>Meaning</th>
- <th>Gender</th>
- </tr>
- <?php foreach($model as $field){ ?>
- <tr>
- <td><?= $field->name; ?></td>
- <td><?= $field->meaning; ?></td>
- <td><?= $field->gender; ?></td>
- <td><?= Html::a("Edit", ['child/edit', 'id' => $field->id]); ?> | <?= Html::a("Delete", ['child/delete', 'id' => $field->id]); ?></td>
- </tr>
- <?php } ?>
Step 4 Run it
Run it on the browser,.
http://localhost/read/frontend/web/index.php?r=child%2Findex
0 Comments