Yii2 DropdownList 值未被发送到模型。

huangapple go评论58阅读模式
英文:

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:

&lt;select id=&quot;singleregisterform-titleid&quot; name=&quot;SingleRegisterForm[titleId]&quot;&gt;
&lt;option value=&quot;1&quot;&gt;Dr&lt;/option&gt;
&lt;option value=&quot;2&quot;&gt;Miss&lt;/option&gt;
&lt;option value=&quot;3&quot;&gt;Mr&lt;/option&gt;
&lt;option value=&quot;4&quot;&gt;Mrs&lt;/option&gt;
&lt;option value=&quot;5&quot;&gt;Ms&lt;/option&gt;
&lt;option value=&quot;6&quot;&gt;Prof&lt;/option&gt;
&lt;/select&gt;

When I submit my form I can see this in the app.log file:

&#39;SingleRegisterForm&#39; =&gt; [
    &#39;titleId&#39; =&gt; &#39;1&#39;
    &#39;firstName&#39; =&gt; &#39;Kate&#39;
    &#39;lastName&#39; =&gt; &#39;Becky&#39;

But when the Model tries to do the save:

$person = new Person();
$person-&gt;title_id = $this-&gt;titleId;
$person-&gt;firstname = $this-&gt;firstName;
$person-&gt;lastname = $this-&gt;lastName;
$person-&gt;save();

I get this error:

COLUMN title_id cannot be NULL.
INSERT INTO `person_register` (`title_id`, `firstname`, `lastname`) VALUES (NULL, &#39;Kate&#39;, &#39;Becky&#39;);

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:

[&#39;titleId&#39;, &#39;required&#39;],

Now it works perfectly.

huangapple
  • 本文由 发表于 2023年2月19日 01:00:47
  • 转载请务必保留本文链接:https://go.coder-hub.com/75494917.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定