在yii2的视图中添加自定义字段,该字段不在模型中 [英] Add custom field in the view of yii2 which is not in model
问题描述
我在 yii2 中保存表单时遇到问题.
I am getting a problem while saving a form in yii2.
我创建了一个自定义字段,其名称与其他字段Myposts['categoryLevel2']
一样.此字段不在模型中.它是一个条件字段.当我发布我的 from 时,我将其值分配给模型属性,例如:
I have created a custom field with name like other fields Myposts['categoryLevel2']
. This field is not in model. It is a conditional field. When I post my from I assign its value to a model attribute Like:
$categoryLevel3 = $request->post('categoryLevel3');
if(!empty($categoryLevel3)){
$model->category=$categoryLevel3;
}
现在因为表帖子中没有categoryLevel3,所以它给出了错误.获取未知属性:frontend\models\Posts我知道这个问题.错误是因为在 $_POST
数组中有一个字段 categoryLevel3
现在它不在表中所以 $model->save()
正在抛出异常.我试过 unset($_POST['categoryLevel3'))
但这也不起作用.有人可以帮我吗?
Now because categoryLevel3 is not there in table post so it is giving error.
Getting unknown property: frontend\models\Posts
I know the issue. The error is because in $_POST
array there is a field categoryLevel3
now and it is not in table so $model->save()
is throwing exception. I tried unset($_POST['categoryLevel3'))
but that also did not work. Can anyone help me on this?
如何在视图中创建一个不在表中的文件并在 $model->save
之前忽略它?
How can I create a filed in view which is not in table and ignore it before $model->save
?
推荐答案
在您的后模型类中添加公共属性 'categoryLevel3
.
Add Public property 'categoryLevel3
in Your Post Model Class.
class Post extends yii\db\ActiveRecord{
public $categoryLevel3;
public function rules(){
return [
[''categoryLevel3' , 'required']
...
];
}
}
这篇关于在yii2的视图中添加自定义字段,该字段不在模型中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!