yii2 的一些学习笔记

Yii2 表单

  • 在select 的值中输出空格,也就是不让 Yii2  编码,而是让   起作用.
    dropDownList([0 => ' 我是空格'],['encode' => false])

encode 设为 false 就会显示为 我是空格,我是空格前面会有一个空格占位,有缩进的效果, 而不会原样显示为  我是空格

数据变更比较

场景:有一个字段 status = 'hidden' 编辑了一下,变为 status = 'publish' 这时要根据变更的类型来改变另一个字断的数据 count = 1 是 count 不变,还是加一

看 yiidbBaseActiveRecord::updateInternal 方法中,会把,变更的数据保存到一个 changedAttributes 的数组中,并把 $this->_oldAttributes 中的值设为新值,所以当要做数据的变更比较时可以这样用

/* 是从隐藏到发布 */
$isHiddenToPublish = isset($changedAttributes['status]) ? $changedAttributes['status] : $this->status;

切记不要在 afterSave() 中用 $this->getOldAttribute('status') 来做新值旧值比较,这样会一直是 true, 因为里面已经是新值,不再旧值了。

场景使用

遇到使用场景的情况,新添加一个用户,要插入 username password mail 三个数据,但更新用户时不需要,更改 username,该怎么设置验证呢!
这时场景就派上用场了

控制器中

public function create()
{
    // 新加用户时就可以把场景设置为 create 场景名是随便起的,与在哪个方法中无关
    // 这时 model->rules 中验证只会验证当前场景里有的字段
    // 如果有的验证上带有 on => create 表示这个验证只会在 create场景起作用
    $model->scenario = 'create';
// 如果没有设置场景,默认会把场景设为default,default会调取所有rules里面的字段进行验证
// 如果覆写了 function scenarios() 方法,并在保存数据时没有设置场景就回调用 default场景

}

public function update()
{
// 更改用户时就可以把场景设置为 update
// 这时 model->rules 中的验证,就只有 on => update 和 不带 on 的起作用
$model->scenario = 'update';
}

model

public function rules()
{
    return [
        [['username','password','password_confirm','mail'],'required','on' => 'create'],[['mail'],'on' => 'update'],[['username'],'match','pattern' => '/^[0-9a-zA-Z_]{2,32}$/','message' => '不合法的{attribute}'],'email']
    ];
}

public function scenarios()
{
return [
'create' => ['username','create' => ['mail'],];
}

有个地方要注意,使用了场景后,获取的数据只会是当前场景的,不会有其他场景的数据

如:username password mail
username password mail on => create
mail on => update
在更新时,只会获取 mail 的数据
但在创建时会获取 username password mail 的数据

Yii2国际化支持

组件是 yii\i18n\I18N

翻译使用 Yii::t($category,$message) 第一个参数指储存消息来源的类别名称,第二个参数指需要被翻译的消息.

$category 对应下面的 base

$messageFile = Yii::getAlias($this->basePath) . "/$language/"; // $this->basePath 就是下面的 basePath
if (isset($this->fileMap[$category])) {
    $messageFile .= $this->fileMap[$category];
} else {
    $messageFile .= str_replace('\\','/',$category) . '.php';
}

按照上面的方法,路径就是这样的
@app/messages/{language}/base.php 如果语言是 zh-CN 那就是 @app/messages/zh-CN/base.php

'i18n' => [
            // 'class' => 'yii\i18n\I18N','translations' => [
                'base' => [
                    'class' => '\yii\i18n\PhpMessageSource','basePath' => '@app/messages','forceTranslation' => true,// 默认是 false,表示 sourceLanguage 和 language 相同不翻译,true 就是相同也翻译
                    'fileMap' => [
                        'base' => 'base.php',],

操作 action

不管是内连操作,还是独立操作,都会执行先执行 runWithParams 方法

public function createAction($id)
{
    if ($id === '') {
        $id = $this->defaultAction;
    }
$actionMap = $this->actions(); // 独立方法
if (isset($actionMap[$id])) {
    return Yii::createObject($actionMap[$id],[$id,$this]);

// 下面是内连方法
} elseif (preg_match('/^[a-z0-9\\-_]+$/',$id) && strpos($id,'--') === false && trim($id,'-') === $id) {
    $methodName = 'action' . str_replace(' ','',ucwords(implode(' ',explode('-',$id))));
    if (method_exists($this,$methodName)) {
        $method = new \ReflectionMethod($this,$methodName);
        if ($method->isPublic() && $method->getName() === $methodName) {
            return new InlineAction($id,$this,$methodName);
        }
    }
}

return null;

}

// 执行 runWithParams() 方法时会执行 beforeRun() run() afterRun()
if ($this->beforeRun()) {
$result = call_user_func_array([$this,'run'],$args);
$this->afterRun();

return $result;

} else {
return null;
}

if ($runAction && $this->beforeAction($action)) {
// run the action
$result = $action->runWithParams($params);

$result = $this->afterAction($action,$result);

// call afterAction on modules
foreach ($modules as $module) {
    /* @var $module Module */
    $result = $module->afterAction($action,$result);
}

}

相关文章

学习编程是顺着互联网的发展潮流,是一件好事。新手如何学习...
IT行业是什么工作做什么?IT行业的工作有:产品策划类、页面...
女生学Java好就业吗?女生适合学Java编程吗?目前有不少女生...
Can’t connect to local MySQL server through socket \'/v...
oracle基本命令 一、登录操作 1.管理员登录 # 管理员登录 ...
一、背景 因为项目中需要通北京网络,所以需要连vpn,但是服...