YII学习之表单提交
模型 [EntryForm.php]:
<?php namespace app\models; use yii\baseModel; class EntryForm EXTENDS Model{ public $name; public $email; public function rules() { return [ [['name','email'],'required','message'=>'请填写!'], ['email','email','message'=>'邮箱格式不正确!'] ]; } }控制器 [IndexController.php]:
<?php namespace app\controllers; use Yii; use yii\web\controller; use app\models\EntryForm; class IndexController extends controller { public function actionEntry() { //关闭页面布局 $this->layout = false; //创建表单模型 $entry = new EntryForm(); //如果是Post请求提交 if(Yii::$app->request->getIsPost()){ //获取表单数据给变量post $post = Yii::$app->request->post(); //表单模型设置属性为post $entry->setAttributes($post); //表单模型数据验证 if ($entry->validate()) { //正确 var_dump($post); } else { //返回错误提示 var_dump($entry->getErrors()); } }else{ //如果不是Post请求,正常显示模板 return $this->render('entry',['model'=>$entry]); } } }视图 [index/entry.php]:
<?php use yii\helpers\Url; ?> <form value="<?php echo Url::to(['index/entry']); ?>" method="post"> <input type="text" name="_csrf" value="<?php echo Yii::$app->getRequest()->getCsrfToken(); ?>" /> <input name="name" type="text" /> <input name="email" type="text" /> <input type="submit" value="提交" /> </form>这里没有用YII提供的表单组件及Html的帮助类,前端自定义代码!