Yii的布局与表单提交

布局

定义父模板

1
2
3
4
5
6
在类中定义
public $layout='home';
view的 layout目录添加home.php
body中+<?=$content ;?>

页面中引入其他页面 <php echo $this->render('about');?>

向layout中传入变量

参考链接:https://blog.csdn.net/u012119576/article/details/52633762

方案1:控制器内成员变量

1
2
public $layout = false; //不使用布局
public $layout = "main"; //设置使用的布局文件

方案2:控制器成员方法内

1
2
$this->layout = false; //不使用布局
$this->layout = "main"; //设置使用的布局文件

方案3:视图中选择布局

1
2
$this->context->layout = false; //不使用布局
$this->context->layout = 'main'; //设置使用的布局文件

gii

它的模型生成器非常方便 可以帮助我们生成代码 避免了 我们的重复劳作

https://blog.csdn.net/qq_36431213/article/details/72853671

表单提交CSRF

Yii2表单提交默认需要验证CSRF,如果CSRF验证不通过,则表单提交失败,解决方法

用yii2框架自带的表单,则自带了csrf

yii2高级版的name值分前后台区分

表单中

1
<input type="text" name="_csrf-frontend" value="<?= Yii::$app->request->csrfToken ?>" />(前台实例)

AJAX中加入_csrf字段

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
var csrfToken = $('meta[name="csrf-token"]').attr("content");
$.ajax({
type: 'POST',
url: url,
data: {_csrf:csrfToken},
success: success,
dataType: dataType
});

$.ajax({
 url:'<?php echo Url::to(['login/register-do']);?>',
type: 'POST',
data: formData,
headers: {
"<?php echo yii\web\Request::CSRF_HEADER; ?>" : "<?php echo Yii::$app->request->csrfToken;?>" //csrf
},
//这两个设置项必填
contentType: false,
processData: false,
success:function(data){
// console.log(data);
layer.msg(data.msg,{icon:data.code});
if(data.code == 1){
window.location.href="<?php echo Url::toRoute(['/login/login']);?>";
}
}

控制器设置

1
public $enableCsrfValidation = false;//关闭

全局设置

yii\web\request中的enableCookieValidation默认设置为true的,也就是默认开启csrf的(全局),因为这是全局的,所以在任何的post请求都会要求认证。我们在post数据的时候,就必须设置csrf的数据隐藏在表单中。

关键词和描述

https://jingyan.baidu.com/article/9f63fb916254e6c8400f0ebb.html

表单提交组件

http://www.xiaochengfu.com/index.php/index/detail/aid/64.html

富文本编辑器

参考链接:http://www.imooc.com/article/details/id/289193

1
2
下载kucha/ueditor
$ php composer.phar require kucha/ueditor "*"

controller:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public function actions()
{
return [
'upload' => [
'class' => 'kucha\ueditor\UEditorAction',
'config' => [
"imageUrlPrefix" => '',//图片访问路径前缀
"imagePathFormat" => "/upload/image/{yyyy}{mm}{dd}/{time}{rand:6}", //上传保存路径
"imageFieldName" => "91",
"imageActionName" => "uploadimage", //这里uploadimage一定要用小写,请求的时候,会自动拼接action 上去
"imageRoot" => Yii::getAlias("@webroot")
],
]
];
}

View:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
<?php $form = ActiveForm::begin(); ?>
<?= $form->field($model, 'title')->textInput(['maxlength' => true, 'style'=>'width:200px']) ?>

<?= $form->field($model, 'keywords')->textInput(['maxlength' => true, 'style'=>'width:200px']) ?>
<?= $form->field($model, 'digest')->textInput(['maxlength' => true, 'style'=>'width:200px']) ?>
<?= $form->field($model, 'type')->dropDownList($type, ['style'=>'width:200px']) ?>
<div style="width: 500px">
<?= $form->field($model, 'logo')->label('图片')->widget('manks\FileInput', []) ?>
</div>
<!-- 详情描述-->
<?= $form->field($model, 'content')->widget('kucha\ueditor\UEditor',[
'clientOptions' => [
//编辑区域大小
'initialFrameHeight' => '200',
//设置语言
'lang' =>'zh-cn', //中文为 zh-cn
//定制菜单
'toolbars' => [
[
'fullscreen', 'source', 'undo', 'redo', '|',
'fontsize',
'bold', 'italic', 'underline', 'fontborder', 'strikethrough', 'removeformat',
'formatmatch', 'autotypeset', 'blockquote', 'pasteplain', '|',
'forecolor', 'backcolor', '|',
'lineheight', '|',
'indent', '|','simpleupload','insertimage','justifyleft', 'justifyright', 'justifycenter', 'justifyjustify', //两端对齐
],
]
]
]
) ?>
<?= $form->field($model, 'recommend')->radioList(['1'=>'是','0'=>'否']) ?>
<?= $form->field($model, 'sorts')->textInput(['maxlength' => true, 'style'=>'width:100px','placeholder'=>'越大越靠前']) ?>
<div class="form-group">
<?= Html::submitButton('保存', ['class' => 'btn btn-success']) ?>
</div>

<?php ActiveForm::end(); ?>

分页

controller

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
$pageSize=5;//相关栏目分页
if(isset($get['type'])){
$catgory=$model->find()->where('type=:type')->addParams([':type'=>intval($get['type'])]);
}else{
$catgory=$model->find()->where('type=:type')->addParams([':type'=>1]);
}
// dd($catgory->count());
$pages=new Pagination([
//总的记录条数
'totalCount' => $catgory->count(),
//分页大小
'pageSize' => $pageSize,
//设置地址栏当前页数参数名
'pageParam' => 'p',
//设置地址栏分页大小参数名
'pageSizeParam' => 'pageSize',
]);
$catgory=$catgory->orderBy('sorts desc , addtime desc')
->offset($pages->offset)
->limit($pages->limit)
->asArray()
->all();

view:

1
2
3
4
5
6
7
8
9
10
<?php endforeach; ?>
<?= \yii\widgets\LinkPager::widget([
'pagination' => $pages,
'firstPageLabel' => '首页',
'lastPageLabel' => '尾页',
'nextPageLabel' => '下一页',
'prevPageLabel' => '上一页',
//设置class样式
'options' => ['class' => 'pagination'],
]) ?>

文章详情页,上一篇和下一篇

1
2
3
4
5
6
7
//上一篇
$prev=$model->find()->Where('type=:type and id <:id')->addParams([':type'=>$type,':id'=>intval($get['id'])])
->orderBy(['id' => SORT_DESC])->limit(1)->asArray()->one();
// dd($prev);
//下一篇
$next=$model->find()->Where('type=:type and id >:id')->addParams([':type'=>$type,':id'=>intval($get['id'])])
->orderBy(['id' => SORT_DESC])->limit(1)->asArray()->one();

参考链接:https://blog.csdn.net/tjls2008/article/details/91411454

设置helper函数

1
common\Helper.php

搜索

1
$search=$help->find()->select('name1')->where('question like :keywords')->orWhere('answer like :keywords')->addParams([':keywords'=>'%' .$post['key'] .'%']);

判断是否ajax请求

1
2
3
if (Yii::$app->request->isAjax) {
return pagine(Pattern::find(), 'id desc');
}

yii2adavnce对layui表格中的字段数据做判断

https://www.cnblogs.com/yachyu/p/10768252.html

1
2
3
4
5
6
7
8
9
10
11
12
13
<script type="text/javascript" id="types">
{{# if (d.type == '1') { }}
<span >主题1</span>
{{# } else if(d.type == '2') { }}
<span >主题2</span>
{{# } else if(d.type === '3') { }}
<span >主题3</span>
{{# } else if(d.type === '4') { }}
<span >主题4</span>
{{# } }}
</script>

{field:'type', title:'主题1',templet:'#types'},