关于定义场景,在load时候,进入Model.safeAttributes方法,类型转换报错。

文档问题 · lesvere · 于 6年前 发布 · 2239 次阅读

在LoginForm中定义了如下方法

class LoginForm extends Model {

const SCENARIO_LOGIN = 'login';

public $username;
public $password;
public $rememberMe = true;

private $_user;

public function scenarios()
{
    $scenarios                         = parent::scenarios();
    $scenarios[self::SCENARIO_LOGIN]   = [
        ['username', 'password'], 'required'
    ];
    $scenarios[self::SCENARIO_DEFAULT] = [
        [['username', 'password'], 'required'],
        ['rememberMe', 'boolean'],
        ['password', 'validatePassword'],
    ];
    return $scenarios;
}

获取实例并应用SCENARIO_LOGIN场景,在load时候,进入方法Model.safeAttributes(),进入Model.setAttributes(),进入Model.safeAttributes()方法,该方法中便利了场景,

/**

 * Returns the attribute names that are safe to be massively assigned in the current scenario.
 * @return string[] safe attribute names
 */
public function safeAttributes()
{
    $scenario = $this->getScenario();
    $scenarios = $this->scenarios();
    if (!isset($scenarios[$scenario])) {
        return [];
    }
    $attributes = [];
    foreach ($scenarios[$scenario] as $attribute) {
	// 问题在if判断里面
       if ($attribute[0] !== '!' && !in_array('!' . $attribute, $scenarios[$scenario])) {
            $attributes[] = $attribute;
        }
    }

    return $attributes;
}

上面43行,这行中 '!' . $attribute,由于$scenarios[$scenario]是数组,[['username', 'password'], 'required'],故而报Array convert to string 的错。

共收到 3 条回复 问题提问
lesvere#16年前 0 个赞

解决了

rules的规则为,三唯数组

lesvere#26年前 0 个赞

$scenarios[self::SCENARIO_LOGIN] = [

        [['username', 'password'], 'required']
    ];

错误示范: $scenarios[self::SCENARIO_LOGIN] = [

        ['username', 'password'], 'required',
    ];
lesvere#36年前 0 个赞

信息:在上述和下述的例子中,模型类都是继承yii\db\ActiveRecord, 因为多场景的使用通常发生在Active Record 类中.

添加回复 (需要登录)
需要 登录 后方可回复, 如果你还没有账号请点击这里 注册
Your Site Analytics