CHtml是一个静态类,提供了一个用于创建HTML视图的辅助方法。
–YII手册
user.php
仅仅是为了测试
public static function getCitys()
{
$citys = Yii::app()->db->createCommand()->select('id,name')->from('city')->queryAll();
$citys = CHtml::listData($citys,'id' , 'name'); //转换成一维数组
return $citys;
}
html.php
<h1>新增用户</h1>
<?php echo CHtml::beginForm("", "POST");?>
<div class="form">
<?php echo CHtml::label("用户名", "username");?>
<?php echo CHtml::textField("username");?>
<?php echo CHtml::label("城市", "city");?>
<?php echo CHtml::dropDownList("city", "", User::getCitys(),array('prompt'=>'请选择'));?>
<?php echo CHtml::submitButton('新增',array('name'=>''));?>
</div>
<?php echo CHtml::endForm();?>
public function actionHtml()
{
if(Yii::app()->request->isPostRequest)
{
$user = new User;
$user->username = $_POST['username'];
$user->city = $_POST['city'];
if($user->save())
{
var_dump("新增成功,id为".$user->id);
} else {
var_dump($user->errors);
}
}
$this->render('html');
}