You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Yii2 DropdownList值未传递至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'
]

但执行Model保存操作时:

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

出现错误:

COLUMN title_id cannot be NULL.
INSERT INTO `person_register` (`title_id`, `firstname`, `lastname`) VALUES (NULL, 'Kate', 'Becky');
解决方法

从日志看表单参数已经正确提交,但$this->titleId没有拿到值,导致title_id为NULL,按以下步骤排查修复:

  • 检查表单模型的属性声明
    如果用的是Yii框架的SingleRegisterForm模型,需要确保模型里声明了titleId属性,同时添加安全验证规则:

    class SingleRegisterForm extends Model
    {
        public $titleId;
        public $firstName;
        public $lastName;
    
        public function rules()
        {
            return [
                [['titleId', 'firstName', 'lastName'], 'safe'],
                // 其他验证规则...
            ];
        }
    }
    
  • 确认表单数据已加载到模型
    在控制器处理提交的逻辑中,必须先把POST数据加载到SingleRegisterForm实例,否则模型拿不到对应值:

    $model = new SingleRegisterForm();
    if ($model->load(Yii::$app->request->post())) {
        $person = new Person();
        $person->title_id = $model->titleId;
        $person->firstname = $model->firstName;
        $person->lastname = $model->lastName;
        $person->save();
    }
    

    你代码里的$this如果不是指向已加载数据的SingleRegisterForm实例,自然拿不到titleId。

  • 直接从POST请求中取值兜底
    如果以上方法仍有问题,可以直接从POST数组中获取对应值:

    $formData = Yii::$app->request->post('SingleRegisterForm');
    $person = new Person();
    $person->title_id = $formData['titleId'];
    $person->firstname = $formData['firstName'];
    $person->lastname = $formData['lastName'];
    $person->save();
    

内容的提问来源于stack exchange,提问作者Quentinb

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.31 09:02:52