(新手求助)AR接收不到表单数据 [ 2.0 版本 ]
use yii\helpers\Html;
use yii\bootstrap\ActiveForm;
use frontend\models\Post;
$this->title = '发帖';
$this->params['breadcrumbs'][] = $this->title;
<?php $form=ActiveForm::begin([
'id' => 'post-form',
'options' => ['class' => 'class_name'],
'action'=>'index.php?r=index/post',
'method'=>'post',
]);
?>
<?= $form->field($model,'title')->textInput()->label('标题');?>
<?= $form->field($model,'content')->textarea(['rows'=>6,'id'=>'editor','class'=>'col-sm-1 col-md-12'])->label('文章');?>
<div class="form-group">
<?= Html::submitButton('提交', [
'class'=>'btn btn-primary',
'name' =>'submit-button'])?>
</div>
<?php ActiveForm::end();?>
view
namespace frontend\controllers;
use yii;
use frontend\models\Post;
use yii\web\Controller;
class IndexController extends Controller{
public function actionIndex(){
// $model =new Post();
return $this->render('post',[
'model' => new Post()
]);
}
public function actionPost(){
$model =new Post();
if(yii::$app->request->post())
{
$model->title=yii::$app->request->post('title');
$model->content=yii::$app->request->post('content');
$model->save();
return $this->render('post_success',[
'model'=>$model
]);
}
else
{
return $this->render('post',[
'model'=>$model
]);
}
}
}
controller
namespace frontend\models;
use Yii;
class Post extends \yii\db\ActiveRecord
{
public $title;
public $content;
public static function tableName()
{
return 'post';
}
public function rules()
{
return [
[['title'], 'required','message' => '标题不能为空.'],
[['content'],'required','message' => '文章内容不能为空.'],
[['title'], 'string', 'max' => 50],
[['content'], 'string', 'max' => 200],
];
}
public function attributeLabels()
{
return [
'id' => 'ID',
'title' => 'Title',
'content' => 'Content',
];
}
}
model
刚接触YII的一个新手
最佳答案
-
你要看一下 HTML 上的 ActiveForm
input tag name ="xxxx" or name="ModelName[xxx]"
你取用的方式是 name = "xxxx"
我記得ActiveForm 是已陣列方式呈現 name ="ModelName[......]"如果不確定的話:
你大可直接 $_POST 看看傳入值是長甚麼樣子共 2 条回复public function actionCreate() { $model = new CrmCars(); if ($model->load(Yii::$app->request->post()) && $model->save()) { return $this->redirect(['view', 'id' => $model->id]); } else { return $this->render('create', [ 'model' => $model, ]); } }
按照官网这样做最安全了,也省事
另外模型用gii生成,别自己手写@qq3737002 谢谢!
liluoao , fantasy2012 觉得很赞
其他 1 个回答
liluoao 杭州
注册时间:2015-12-26
最后登录:2023-09-30
在线时长:20小时13分
最后登录:2023-09-30
在线时长:20小时13分
- 粉丝6
- 金钱10510
- 威望0
- 积分10710