YII 使用表单的三种方式

原生HTML表单

<div class="form">
    <h1>添加新的用户</h1>
    <form method="POST">
        <div class="row">
            <label>用户名</label>
            <input type="text" name="username" value=""/>
        </div>
        <div class="row">
            <label>城市</label>
            <select name="city_id">
                <?php echo User::getCityOptions();?>
            </select>
        </div>
        <div class="row">
            <input type="submit" value="添加">
        </div>
    </form>
</div>

ACTION:

public function actionHtml(){
        //如果有表单提交,则给user对象赋值
        if(!empty($_POST)){
            //实例化user模型
            $model = new User();
            $now = time();
//            dump($_POST);
            $model->username = $_POST['username'];
            $model->city_id = $_POST['city_id'];
            $model->create_time = $now;
            $model->update_time = $now;
            if(!$model->save()){
                dump($model->getErrors());
            }else{
                dump('保存成功');
            }
        }
        //渲染视图html并传入Model参数
        $this->render('html');
    }

在模型中读取城市信息:

public static function getCityOptions(){
            $option = '<option value="">请选择</option>';
            $citys = self::getCitys();
            if(!empty($citys)){
                foreach ($citys as $v=>$name) {
                    $option.= "<option value={$v}>$name</option>";
                }
            }
            return $option;
        }
 
        public static function getCitys(){
            $citys = Yii::app()->db->createCommand()->select('id,name')->from('city')->queryAll();
            if(!empty($citys)){
                $citys = CHtml::listData($citys, 'id', 'name');
            }
            return $citys;
        }

CHtml:

<div class="form">
    <h1>添加新的用户</h1>
    <?php echo CHtml::beginForm('', 'POST');?>
        <div class="row">
            <?php echo CHtml::label('用户名', 'username');?>
            <?php echo CHtml::textField('username', '');?>
        </div>
        <div class="row">
            <?php echo CHtml::label('城市', 'city_id')?>
            <?php echo CHtml::dropDownList('city_id', '', User::getCitys())?>
        </div>
        <div class="row">
            <?php echo CHtml::submitButton('添加')?>
        </div>
    <?php echo CHtml::endForm();?>
</div>

action:

public function actionChtml(){
        if(!empty($_POST)){
            $now = time();
            $model = new User();
            //将post提交的值赋值给attributes属性
            $model->attributes = $_POST;
//            dump($model->attributes);
            $model->create_time = $now;
            $model->update_time = $now;
            if(!$model->save()){
                dump($model->getErrors());
            }else{
                dump('添加成功');
            }
        }
 
        $this->render('chtml');
    }

CActiveForm:

<?php $form=$this->beginWidget('CActiveForm', array(
	'id'=>'user-active_form-form',
	// Please note: When you enable ajax validation, make sure the corresponding
	// controller action is handling ajax validation correctly.
	// See class documentation of CActiveForm for details on this,
	// you need to use the performAjaxValidation()-method described there.
	'enableAjaxValidation'=>true,
//        'enableClientValidation'=>true,
)); ?>
 
	<p class="note">带 <span class="required">*</span> 为必填项.</p>
 
	<?php echo $form->errorSummary($model); ?>
 
	<div class="row">
		<?php echo $form->labelEx($model,'username'); ?>
		<?php echo $form->textField($model,'username'); ?>
		<?php echo $form->error($model,'username'); ?>
	</div>
 
	<div class="row">
		<?php echo $form->labelEx($model,'city_id'); ?>
                <?php echo $form->dropDownList($model,'city_id',User::getCitys(),array('prompt'=>'请选择'));?>
		<?php echo $form->error($model,'city_id'); ?>
	</div>
 
	<div class="row buttons">
		<?php echo CHtml::submitButton($model->isNewRecord?'添 加':'修 改'); ?>
	</div>
 
<?php $this->endWidget(); ?>

action:

public function actionActiveform(){
        $model=new User;
 
        // uncomment the following code to enable ajax-based validation
        /*
        if(isset($_POST['ajax']) && $_POST['ajax']==='user-active_form-form')
        {
            echo CActiveForm::validate($model);
            Yii::app()->end();
        }
        */
 
        if(isset($_POST['User']))
        {
            $model->attributes=$_POST['User'];
            if($model->validate())
            {
                // form inputs are valid, do something here
                return;
            }
        }
        $this->render('active_form',array('model'=>$model));
    }

CForm:
action

 public function actionForm(){
        $model = new User();
        $form = new CForm($model->getFMConfig(), $model);
        $this->peformAjaxValidate($model);
        if($form->submitted() && $form->validate()){
            if($model->save()){
                dump('数据添加成功,新添加的id为'.$model->id);
            }
        }
        $this->render('form',array(
            'form'=>$form,
        ));
    }

model:

 public function getFMConfig(){
        return array(
            'title'=>'用户添加表单',
            'description'=>'用户添加表单2',
            'method'=>'post',
            'attributes'=>array(
                'class'=>'cform'
            ),
            'showErrorSummary'=>true,
            'showErrors'=>true,
            'activeForm'=>array(
                'class'=>'CActiveForm',
                'id'=>'user-active_form-form',
            ),
            'elements'=>array(
                'username'=>array(
                    'type'=>'text',
                    'hint'=>'请输入用户名',
                    'enableAjaxValidation'=>true,
                    'enableClientValidation'=>true,
 
                ),
                'city_id'=>array(
                    'type'=>'dropdownlist',
                    'prompt'=>'请选择',
                    'items'=>User::getCitys(),
                )
            ),
            'buttons'=>array(
                'submit'=>array(
                    'type'=>'submit',
                    'label'=>'提交',
                )
            )
        );
    }

views:

<div class="form">
    <?php echo $form->render();?>
</div>

发表评论

电子邮件地址不会被公开。 必填项已用*标注