tjtjtjのメモ

自分のためのメモです

yiiを使ってみる2

Userを一覧表示するページを作る。前回yiicを使ってCRUDページを生成した。まずはindexページを作れるようになることが今回のゴール。ただしモデルはyiicシェルで生成したものを使いまわす。

コントローラーのみ

コントローラー作成

yiiprac1\protected\controllers\User2Controller.php

<?php
class User2Controller extends Controller
{
	public function actionIndex() {
		echo "User2Controller::actionIndex";
	}
}
確認

http://localhost/yiiprac1/index.php?r=user2

echoしたものが表示されている。

コントローラーとビュー

コントローラーをビューを使うように修正し

yiiprac1\protected\controllers\User2Controller.php

<?php
class User2Controller extends Controller
{
	public function actionIndex() {
		$this->render('index');
	}
}
ビューを作成

yiiprac1\protected\views\user2\index.php

User2/index
確認

http://localhost/yiiprac1/index.php?r=user2

view に記述した「User2/index」が表示されている。

ビューに値を渡す

コントローラーの変数をrendarに渡して

yiiprac1\protected\controllers\User2Controller.php

<?php
class User2Controller extends Controller
{
	public function actionIndex() {
		$val = "User2Controller::actionIndex";
		$this->render('index', array('val'=>$val));
	}
}
ビューで変数をecho

yiiprac1\protected\views\user2\index.php

User2/index
<?php
echo "[".$val."]";
確認

http://localhost/yiiprac1/index.php?r=user2

view に渡した「User2Controller::actionIndex」が表示されている。

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はあとで調べよう。