This is an example how to combine Yii2 with AngularJS. We have one table, game.
1. Table Preparation
Table game :
Create model Game.php using Gii, put it in common\models folder.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 |
<?php namespace common\models; use Yii; /** * This is the model class for table "game". * * @property integer $id * @property string $console * @property string $name * @property string $year */ class Game extends \yii\db\ActiveRecord { /** * @inheritdoc */ public static function tableName() { return 'game'; } /** * @inheritdoc */ public function rules() { return [ [['console', 'name'], 'string', 'max' => 255], [['year'], 'string', 'max' => 11], ]; } /** * @inheritdoc */ public function attributeLabels() { return [ 'id' => Yii::t('app', 'ID'), 'console' => Yii::t('app', 'Console'), 'name' => Yii::t('app', 'Name'), 'year' => Yii::t('app', 'Year'), ]; } } |
2. Create GameController.php, index.php, app.js and Use AngularJS 1.6
create frontend/controllers/GameController.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
<?php namespace frontend\controllers; use Yii; use yii\web\Controller; use common\models\Game; class GameController extends Controller{ public function beforeAction($action){ $this->enableCsrfValidation = false; return parent::beforeAction($action); } public function actionIndex(){ return $this->render('index'); } } |
create frontend/views/game/index.php
Use AngularJS 1.6, and put https://ajax.googleapis.com/ajax/libs/angularjs/1.6.7/angular.min.js inside this file.
1 2 3 4 5 6 7 8 |
<div ng-app="App" ng-controller="AppCtrl"> <h4>{{6+4}}</h4> </div> <?php echo $this->registerJsFile("https://ajax.googleapis.com/ajax/libs/angularjs/1.6.7/angular.min.js"); echo $this->registerJsFile("js/app.js"); ?> |
create frontend/web/app.js
1 2 3 4 |
var app = angular.module("App",[]); app.controller("AppCtrl",function($scope,$http){ }); |
If the result of {{6+4}} has become 10, it means the AngularJS has already running:
3. Create the List
modify frontend/view/game/index.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 |
<div ng-app="App" ng-controller="AppCtrl"> <fieldset> <legend>Game List</legend> <table class="table"> <thead> <th>#</th> <th>Console</th> <th>Game Name</th> <th>Year</th> </thead> <tbody> <tr> <td></td> <td> <input placeholder="Console" type="text" class="form-control" ng-model="data.console" /> </td> <td> <input placeholder="Game Name" type="text" class="form-control" ng-model="data.name" /> </td> <td> <input placeholder="Year" type="text" class="form-control" ng-model="data.year" /> </td> <td> <button class="btn btn-primary" ng-click="save()">Save</button> </td> </tr> </tbody> </table> </fieldset> </div> <?php echo $this->registerJsFile("https://ajax.googleapis.com/ajax/libs/angularjs/1.6.7/angular.min.js"); echo $this->registerJsFile("js/app.js"); ?> |
I put a record through mySql to test the data display.
Modify app.js by adding gameList function:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
var app = angular.module("App",[]); app.controller("AppCtrl",function($scope,$http){ $scope.gameList = function(){ $http.get( 'index.php?r=game/game-list' ).then(successCallback, errorCallback); function successCallback(success){ $scope.allGames = success.data; } function errorCallback(error){ alert("Fetch Data Error"); } }; $scope.gameList(); }); |
Modify GameController.php by adding public function actionGameList() :
1 2 3 4 |
public function actionGameList(){ $games = Game::find()->orderBy('id DESC')->asArray()->all(); return json_encode($games); } |
4. Add a Record
Modify GameController.php, add public function actionCreate():
1 2 3 4 5 6 7 8 9 10 |
public function actionCreate(){ $postData = file_get_contents("php://input"); $dataObject = json_decode($postData); $game = new Game(); $game->console = $dataObject->data->console; $game->name = $dataObject->data->name; $game->year = $dataObject->data->year; $game->save(); } |
Modify app.js, add
1 2 |
$scope.action = "create"; $scope.data = {}; |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 |
$scope.save = function(){ switch($scope.action){ case "create": $scope.createRecord(); break; case "update": $scope.updateRecord(); break; }; }; $scope.clearData = function(){ $scope.data = { console : "", name : "", year : "" }; }; $scope.createRecord = function(){ $http.post( 'index.php?r=game/create', { data: $scope.data } ).then(successCallback, errorCallback); function successCallback(response){ $scope.clearData(); $scope.gameList(); }; function errorCallback(error){ alert("Create Data Error"); }; }; |
Add one record and click Save, data will automatically stored in the database.
5. Update Record
Modify GameController.php, add public function actionUpdate.
1 2 3 4 5 6 7 8 9 10 |
public function actionUpdate(){ $postData = file_get_contents("php://input"); $dataObject = json_decode($postData); $game = Game::findOne($dataObject->data->id); $game->console = $dataObject->data->console; $game->name = $dataObject->data->name; $game->year = $dataObject->data->year; $game->save(); } |
Modify app.js, add
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
$scope.preUpdate = function(game){ $scope.data = game; $scope.action = "update"; } $scope.updateRecord = function(){ $http.post( 'index.php?r=game/update', { data : $scope.data }).then(successCallback, errorCallback); function successCallback(response){ $scope.clearData(); $scope.gameList(); $scope.save = "update"; } function errorCallback(error){ alert("Gagal ubah data"); } } |
Now try to update the Last of Us data by clicking ‘Update’ button, and change the value whatever you want:
Click Save, now the record has changed.
6. Delete Record
Modify GameController.php, add public function actionDelete.
1 2 3 4 5 6 7 |
public function actionDelete(){ $postData = file_get_contents("php://input"); $dataObject = json_decode($postData); $game = Game::findOne($dataObject->id); $game->delete(); } |
Modify app.js, add :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
$scope.delete = function(id){ $http.post( 'index.php?r=game/delete', { id : id } ).then(successCallback, errorCallback); function successCallback(response){ $scope.gameList(); } function errorCallback(error){ alert("Delete Failed"); } }; |
Now try to Delete a record.
So now the files will look like this:
GameController.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 |
<?php namespace frontend\controllers; use Yii; use yii\web\Controller; use common\models\Game; class GameController extends Controller{ public function beforeAction($action){ $this->enableCsrfValidation = false; return parent::beforeAction($action); } public function actionIndex(){ return $this->render('index'); } public function actionGameList(){ $games = Game::find()->orderBy('id DESC')->asArray()->all(); return json_encode($games); } public function actionCreate(){ $postData = file_get_contents("php://input"); $dataObject = json_decode($postData); $game = new Game(); $game->console = $dataObject->data->console; $game->name = $dataObject->data->name; $game->year = $dataObject->data->year; $game->save(); } public function actionUpdate(){ $postData = file_get_contents("php://input"); $dataObject = json_decode($postData); $game = Game::findOne($dataObject->data->id); $game->console = $dataObject->data->console; $game->name = $dataObject->data->name; $game->year = $dataObject->data->year; $game->save(); } public function actionDelete(){ $postData = file_get_contents("php://input"); $dataObject = json_decode($postData); $game = Game::findOne($dataObject->id); $game->delete(); } } |
index.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 |
<div ng-app="App" ng-controller="AppCtrl"> <fieldset> <legend>Game List</legend> <table class="table"> <thead> <th>#</th> <th>Console</th> <th>Game Name</th> <th>Year</th> </thead> <tbody> <tr> <td></td> <td> <input placeholder="Console" type="text" class="form-control" ng-model="data.console" /> </td> <td> <input placeholder="Game Name" type="text" class="form-control" ng-model="data.name" /> </td> <td> <input placeholder="Year" type="text" class="form-control" ng-model="data.year" /> </td> <td> <button class="btn btn-primary" ng-click="save()">Save</button> </td> </tr> <tr ng-repeat="game in allGames"> <td>{{$index+1}}</td> <td>{{game.console}}</td> <td>{{game.name}}</td> <td>{{game.year}}</td> <td> <button class="btn btn-success" ng-click=preUpdate(game)>Update</button> <button class="btn btn-danger" ng-click=delete(game.id)>Delete</button> </td> </tr> </tbody> </table> </fieldset> </div> <?php echo $this->registerJsFile("https://ajax.googleapis.com/ajax/libs/angularjs/1.6.7/angular.min.js"); echo $this->registerJsFile("js/app.js"); ?> |
app.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 |
var app = angular.module("App",[]); app.controller("AppCtrl",function($scope,$http){ $scope.action = "create"; $scope.data = {}; $scope.save = function(){ switch($scope.action){ case "create": $scope.createRecord(); break; case "update": $scope.updateRecord(); break; }; }; $scope.clearData = function(){ $scope.data = { console : "", name : "", year : "" }; }; $scope.createRecord = function(){ $http.post( 'index.php?r=game/create', { data: $scope.data } ).then(successCallback, errorCallback); function successCallback(response){ console.log($scope.data); $scope.clearData(); $scope.gameList(); }; function errorCallback(error){ alert("Create Data Error"); }; }; $scope.preUpdate = function(game){ $scope.data = game; $scope.action = "update"; } $scope.updateRecord = function(){ $http.post( 'index.php?r=game/update', { data : $scope.data }).then(successCallback, errorCallback); function successCallback(response){ $scope.clearData(); $scope.gameList(); $scope.save = "update"; } function errorCallback(error){ alert("Gagal ubah data"); } } $scope.gameList = function(){ $http.get( 'index.php?r=game/game-list' ).then(successCallback, errorCallback); function successCallback(success){ $scope.allGames = success.data; }; function errorCallback(error){ alert("Fetch Data Error"); }; }; $scope.delete = function(id){ $http.post( 'index.php?r=game/delete', { id : id } ).then(successCallback, errorCallback); function successCallback(response){ $scope.gameList(); } function errorCallback(error){ alert("Delete Failed"); } }; $scope.gameList(); }); |
Good luck!