yiiを使ってみる2
Userを一覧表示するページを作る。前回yiicを使ってCRUDページを生成した。まずはindexページを作れるようになることが今回のゴール。ただしモデルはyiicシェルで生成したものを使いまわす。
コントローラーのみ
コントローラー作成
yiiprac1\protected\controllers\User2Controller.php
<?php class User2Controller extends Controller { public function actionIndex() { echo "User2Controller::actionIndex"; } }
コントローラーとビュー
コントローラーをビューを使うように修正し
yiiprac1\protected\controllers\User2Controller.php
<?php class User2Controller extends Controller { public function actionIndex() { $this->render('index'); } }
ビューに値を渡す
コントローラーの変数をrendarに渡して
yiiprac1\protected\controllers\User2Controller.php
<?php class User2Controller extends Controller { public function actionIndex() { $val = "User2Controller::actionIndex"; $this->render('index', array('val'=>$val)); } }
yiicシェルで生成したモデルを使う
コントローラーでモデルをfindAllして
yiiprac1\protected\controllers\User2Controller.php
<?php class User2Controller extends Controller { public function actionIndex() { $users = User::model()->findAll(); $this->render('index', array('users'=>$users)); } }
ビューで変数をecho
yiiprac1\protected\views\user2\index.php
<h1>Users</h1> <ol> <?php foreach($users as $user) : ?> <li> <?php echo $user->username; ?> </li> <?php endforeach; ?> </ol>
確認
http://localhost/yiiprac1/index.php?r=user2
DBの「User.username」が表示されている。最低限必要なのはこんなところか。yiicで生成したコードに含まれていたCActiveDataProviderとかzii.widgets.CListViewはあとで調べよう。