To insert the records in the database, following steps are there. We have named our Yii2 folder as create.
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]
- ];
- }
- }
Look at the above code,
- \yii\db\ActiveRecord is used to create a model file.
- In function tableName put the table name you are using.
- Function rules define the inputs of your table.
Step 2 Create Controllers file
Create a controller file ChildController.php in frontend/controllers folder.
- <?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]);
- }
- }
Step 3 Create View file
Create a view folder child in frontend/views folder. Then create a file create.php in frontend/views/child folder.
- <?= $this->render('child_view', [
- 'model' => $model,
- ]) ?>
Now create a file child_view.php in frontend/views/child folder.
- <?php
- use yii\helpers\Html;
- use yii\widgets\ActiveForm;
- ?>
-
- <?php $form = ActiveForm::begin(); ?>
-
- <?= $form->field($model, 'name'); ?>
- <?= $form->field($model, 'meaning'); ?>
- <?= $form->field($model, 'gender'); ?>
-
- <?= Html::submitButton($model->isNewRecord ? 'Create' : 'Update', ['class' => $model->
- isNewRecord ? 'btn btn-success' : 'btn btn-primary']); ?>
-
- <?php ActiveForm::end(); ?>
Step 4 Run it
Now run your application on your browser with the following URL.
http://localhost/create/frontend/web/index.php?r=child/create
Look at the above snpashot, after filling all the fields click on Create button and your data will be inserted into the database.
You can check it in the database from your phpmyadmin.
0 Comments