英文:
Yii2 DropdownList Value not being sent to Model
问题
我有一个下拉列表,看起来像这样:
<select id="singleregisterform-titleid" name="SingleRegisterForm[titleId]">
<option value="1">Dr</option>
<option value="2">Miss</option>
<option value="3">Mr</option>
<option value="4">Mrs</option>
<option value="5">Ms</option>
<option value="6">Prof</option>
</select>
当我提交表单时,我可以在 app.log 文件中看到这个:
'SingleRegisterForm' => [
'titleId' => '1'
'firstName' => 'Kate'
'lastName' => 'Becky'
]
但是当模型尝试进行保存时:
$person = new Person();
$person->title_id = $this->titleId;
$person->firstname = $this->firstName;
$person->lastname = $this->lastName;
$person->save();
我得到了这个错误:
列 title_id 不能为空。
INSERT INTO `person_register` (`title_id`, `firstname`, `lastname`) VALUES (NULL, 'Kate', 'Becky');
有什么建议吗?
英文:
I have a dropdownList which looks like this:
<select id="singleregisterform-titleid" name="SingleRegisterForm[titleId]">
<option value="1">Dr</option>
<option value="2">Miss</option>
<option value="3">Mr</option>
<option value="4">Mrs</option>
<option value="5">Ms</option>
<option value="6">Prof</option>
</select>
When I submit my form I can see this in the app.log file:
'SingleRegisterForm' => [
'titleId' => '1'
'firstName' => 'Kate'
'lastName' => 'Becky'
But when the Model tries to do the save:
$person = new Person();
$person->title_id = $this->titleId;
$person->firstname = $this->firstName;
$person->lastname = $this->lastName;
$person->save();
I get this error:
COLUMN title_id cannot be NULL.
INSERT INTO `person_register` (`title_id`, `firstname`, `lastname`) VALUES (NULL, 'Kate', 'Becky');
Any ideas?
答案1
得分: 0
这很有趣。我本来以为 Yii2 不会担心不在验证规则中的字段。在我的 DropDownList 中,即使用户没有更改它,它仍然会有一个值,这个值将是 1,即列表中的第一个值。
Yii2 没有将这个值发送回模型,因为我没有将这个字段包括在验证规则中。
我不得不将这个规则添加到我的规则中:
['titleId', 'required'],
现在它完美运行。
英文:
This is very funny. I would have expected Yii2 to not worry about fields which are not part of the validation rules. In this case with my DropDownList, even if the user does not change it, it will still have a value which will be 1, the first one in the list.
Yii2 did not send this back to the Model because I don't have this field as part of the validation rules.
I had to add this to my rules:
['titleId', 'required'],
Now it works perfectly.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论