标签 php 下的文章

Yii的model赋值自定义表单的数据


普通api的接口传递参数时,默认是没有formName的,通常是$_POST或者$_GET,此时是不能直接调用model的load方法进行属性赋值的。
查看load方法的源码

public function load($data, $formName = null)
{
    $scope = $formName === null ? $this->formName() : $formName;
    if ($scope === '' && !empty($data)) {
        $this->setAttributes($data);
    
        return true;
    } elseif (isset($data[$scope])) {
        $this->setAttributes($data[$scope]);

        return true;
    } else {
        return false;
    }
}

则处理方法如下:
方法一:load方法的第二个参数传空字符串'';这种情况就可以给model的属性赋值了。

$model = new UserForm();
$post = ['name' => '小王', 'sex' => '女'];
$model->load($post, '');

方法二:给model的attributes属性赋值

$model = new UserForm();
$post = ['name' => '小王', 'sex' => '女'];
$model->attributes = $post;

此时model的属性就会被赋值。