http://www.phpxs.com/post/yii2/
后台首页编辑 [ 'attribute' => '头像', 'format' => 'raw', 'value' => function ($data) { if(!empty($data->weixin->headimgurl)){ return "<img src=".$data->weixin->headimgurl." class='user-list-headimgurl'>"; } }, ],
增减按钮
<?= Html::a('创建商品', ['create'], ['class' => 'btn btn-success']) ?>
<?= Html::a('批量删除', ['sanger'], ['class' => 'btn btn-danger']) ?>
删除:
['class' => 'yii\grid\CheckboxColumn'],
增删查改:
['class' => 'yii\grid\ActionColumn'],
或
[
'class' => 'yii\grid\ActionColumn', //由于是默认类型,可以省略
'header' => '操作', //标题
'template' => '{view}{delete}{update}', //查看、删除、修改
],
序号:
['class' => 'yii\grid\SerialColumn'],
分页和排序:
在控制器**search‘query’=>$query下增加
//定义哪些可以排序
Yii时间转换
[
'attribute' => 'created_at',
'format' => ['date', 'php:Y-m-d H:i:s'],
设置宽度
'contentOptions'=>['width'=>'110px'],
],
管理表新增字段(且加搜索和排序)
在rules下增加authorName的safe下增加安全字段(查询和排序)
添加Yii::t语言
Mian.php components配置下
'i18n' => [
'translations' => [
'app*' => [
'class' => 'yii\i18n\PhpMessageSource',
//'basePath' => '@app/messages',
'sourceLanguage' => 'en',
'fileMap' => [
'app' => 'app.php',
'app/error' => 'error.php',
],
], ],],
数据关联:
Models:
public functiongetEcmOrderGoods(){
return$this->hasOne(EcmOrderGoods::className(),['order_id'=>'order_id']);
}
views:
‘ecmOrderGoods.goods_name’
生成ID
Yii::$app->db->getLastInsertID();
数据库操作
基础查询
command查询:
$posts=Yii::$app->db->createCommand(‘数据库语句’)->queryAll();
或
$Posts=”查询语句”;
$rows=Yii::$app->db->createCommand($posts);
$store=$rows->queryAll();
Query查询:
$data = (new Query())
->from('数据表')
->join('LEFT JOIN','数据表','关联关系')
->where([‘条件’])
->offset(5)
->limit(10)
->indexBy()索引查询结果
->all()
Find查询:
Allstatus=Customer::find()
->select('*')
->limit(10)
->indexBy()索引查询结果
->all()
Customer::find()->one(); 此方法返回一条数据;
Customer::find()->all(); 此方法返回所有数据;
Customer::find()->count(); 此方法返回记录的数量;
Customer::find()->average(); 此方法返回指定列的平均值;
Customer::find()->min(); 此方法返回指定列的最小值 ;
Customer::find()->max(); 此方法返回指定列的最大值 ;
Customer::find()->scalar(); 此方法返回值的第一行第一列的查询结果;
Customer::find()->column(); 此方法返回查询结果中的第一列的值;
Customer::find()->exists(); 此方法返回一个值指示是否包含查询结果的数据行;
Customer::find()->batch(10); 每次取10条数据
Customer::find()->each(10); 每次取10条数据,迭代查询
Customer::find()->asArray()->one(); 以数组形式返回一条数据;
Customer::find()->asArray()->all(); 以数组形式返回所有数据;
其中$config参数有:
pageSize:设置每页的大小
order:数据的排序
rows:返回的数组中数据对象的键名
pages:返回的数组中分页对象的键名
例子:
//根据sql语句查询:查询name=test的客户
Customer::model()->findAllBySql("select * from customer where name = test");
//根据主键查询:查询主键值为1的数据
Customer::model()->findByPk(1);
//根据条件查询(该方法是根据条件查询一个集合,可以是多个条件,把条件放到数组里面)
Customer::model()->findAllByAttributes(['username'=>'admin']);
//子查询
$subQuery = (new Query())->select('COUNT(*)')->from('customer');
// SELECT `id`, (SELECT COUNT(*) FROM `customer`) AS `count` FROM `customer`
$query = (new Query())->select(['id', 'count' => $subQuery])->from('customer');
//关联查询:查询客户表(customer)关联订单表(orders),条件是status=1,客户id为1,从查询结果的第5条开始,查询10条数据
$data = (new Query())
->select('*')
->from('customer')
->join('LEFT JOIN','orders','customer.id = orders.customer_id')
->where(['status'=>'1','customer.id'=>'1'])
->offset(5)
->limit(10)
//->indexBy()索引查询结果
->all()
直接查询
//createCommand(执行原生的SQL语句)
$sql= "SELECT u.account,i.* FROM sys_user as u left join user_info as i on u.id=i.user_id";
$rows=Yii::$app->db->createCommand($sql);
$store=$rows->queryAll();
查询返回多行:
$command = Yii::$app->db->createCommand('SELECT * FROM post');
$posts = $command->queryAll();
返回单行
$command = Yii::$app->db->createCommand('SELECT * FROM post WHERE id=1');
$post = $command->queryOne();
查询多行单值:
$command = Yii::$app->db->createCommand('SELECT title FROM post');
$titles = $command->queryColumn();
查询标量值/计算值:
$command = Yii::$app->db->createCommand('SELECT COUNT(*) FROM post');
$postCount = $command->queryScalar();
批量查询
Foreach(数据表名::find()->batch(2) as变量){
}
关联查询
/**
*客户表Model:CustomerModel
*订单表Model:OrdersModel
*国家表Model:CountrysModel
*首先要建立表与表之间的关系
*在CustomerModel中添加与订单的关系
*/
Class CustomerModel extends \yii\db\ActiveRecord
{
...
//客户和订单是一对多或多对一的关系所以用hasMany
//此处OrdersModel在CustomerModel顶部别忘了加对应的命名空间
//id对应的是OrdersModel的id字段,order_id对应CustomerModel的order_id字段
public function getOrders()
{
return $this->hasMany(OrdersModel::className(), ['id'=>'order_id']);
}
//客户和国家是一对一的关系所以用hasOne
public function getCountry()
{
return $this->hasOne(CountrysModel::className(), ['id'=>'Country_id']);
}
....
}
// 查询客户与他们的订单和国家
CustomerModel::find()->with('orders', 'country')->all();
// 查询客户与他们的订单和订单的发货地址(注:orders 与 address都是关联关系)
CustomerModel::find()->with('orders.address')->all();
// 查询客户与他们的国家和状态为1的订单
CustomerModel::find()->with([
'orders' => function ($query) {
$query->andWhere('status = 1');
},
'country',
])->all();
条件查询
$customers = Customer::find()->where($cond)->all();
$cond就是我们所谓的条件,条件的写法也根据查询数据的不同存在差异,那么如何用yii2的方式来写查询条件呢?
[[简单条件]]
// SQL: (type = 1) AND (status = 2).
$cond = ['type' => 1, 'status' => 2]
// SQL:(id IN (1, 2, 3)) AND (status = 2)
$cond = ['id' => [1, 2, 3], 'status' => 2]
//SQL:status IS NULL
$cond = ['status' => null]
[[and]]:将不同的条件组合在一起,用法举例:
//SQL:`id=1 AND id=2`
$cond = ['and', 'id=1', 'id=2']
//SQL:`type=1 AND (id=1 OR id=2)`
$cond = ['and', 'type=1', ['or', 'id=1', 'id=2']]
//SQL:`type=1 AND (id=1 OR id=2)` //此写法'='可以换成其他操作符,例:in like != >=等
$cond = [
'and',
['=', 'type', 1],
[
'or',
['=', 'id', '1'],
['=', 'id', '2'],
]
]
[[or]]:
//SQL:`(type IN (7, 8, 9) OR (id IN (1, 2, 3)))`
$cond = ['or', ['type' => [7, 8, 9]], ['id' => [1, 2, 3]]
[[not]]:
//SQL:`NOT (attribute IS NULL)`
$cond = ['not', ['attribute' => null]]
[[between]]: not between 用法相同
//SQL:`id BETWEEN 1 AND 10`
$cond = ['between', 'id', 1, 10]
[[in]]: not in 用法类似
//SQL:`id IN (1, 2, 3)`
$cond = ['in', 'id', [1, 2, 3]] or $cond = ['id'=>[1, 2, 3]]
//IN条件也适用于多字段
$cond = ['in', ['id', 'name'], [['id' => 1, 'name' => 'foo'], ['id' => 2, 'name' => 'bar']]]
//也适用于内嵌sql语句
$cond = ['in', 'user_id', (new Query())->select('id')->from('users')->where(['active' => 1])]
[[like]]:
//SQL:`name LIKE '%tester%'`
$cond = ['like', 'name', 'tester']
//SQL:`name LIKE '%test%' AND name LIKE '%sample%'`
$cond = ['like', 'name', ['test', 'sample']]
//SQL:`name LIKE '%tester'`
$cond = ['like', 'name', '%tester', false]
[[exists]]: not exists用法类似
//SQL:EXISTS (SELECT "id" FROM "users" WHERE "active"=1)
$cond = ['exists', (new Query())->select('id')->from('users')->where(['active' => 1])]
此外,您可以指定任意运算符如下
//SQL:`id >= 10`
$cond = ['>=', 'id', 10]
//SQL:`id != 10`
$cond = ['!=', 'id', 10]
新增
使用model::save()操作进行新增数据
$user= new User;
$user->username =$username;
$user->password =$password;
$user->save()
使用createCommand()进行新增数据
Yii::$app->db->createCommand()->insert('user', [
'name' => 'test',
'age' => 30,
])->execute();
批量插入数据
Yii::$app->db->createCommand()->batchInsert('user', ['name', 'age'], [
['test01', 30],
['test02', 20],
['test03', 25],
])->execute();
修改
使用model::save()进行修改
$user = User::find()->where(['name'=>'test'])->one(); //获取name等于test的模型
$user->age = 40; //修改age属性值
$user->save(); //保存
直接修改:修改用户test的年龄为40
$result = User::model()->updateAll(['age'=>40],['name'=>'test']);
使用createCommand()修改
Yii::$app->db->createCommand()->update('user', ['age' => 40], 'name = test')->execute();
删除
使用model::delete()进行删除
$user = User::find()->where(['name'=>'test'])->one();
$user->delete();
直接删除:删除年龄为30的所有用户
$result = User::deleteAll(['age'=>'30']);
根据主键删除:删除主键值为1的用户
$result = User::deleteByPk(1);
使用createCommand()删除
Yii::$app->db->createCommand()->delete('user', 'age = 30')->execute();
Js/Css用法
在前台view中引入
use yii\helpers\Html;
然后在下面的Html中可以这样调用
Js
<?=Html::jsFile('@web/***/js/***.js')?>//这里***代表你的目录名或者文件名
Css
<?=Html::cssFile('@web/***/css/***.css')?>//***同上
页面中单独写JS(使用数据块)
<div id="mybutton">点我弹出OK</div>
<?php $this->beginBlock('test') ?>
$(function($) {
$('#mybutton').click(function() {
alert('OK');
});
});
<?php $this->endBlock() ?>
<?php $this->registerJs($this->blocks['test'], \yii\web\View::POS_END); ?>
或者:
<?php
$this->registerJs(
'$("document").ready(function(){
$("#login-form").validate({
errorElement : "small",
errorClass : "error",
rules: {
"AgNav[nav_cn]": {
required: true,
},
},
messages:{
"AgNav[nav_cn]" : {
required : "此字段不能为空.",
},
}
});
});'
);
?>
或者:
$cssString = ".gray-bg{color:red;}";
$this->registerCss($cssString);
或者
<?php
$js = <<<JS
(JS语句)
JS;
$this->registerJs($js);
?>
引用JS/CSS文件
yii中的view也使用面向对象方式 ,所以引入CSS和JS文件要用特殊的方法。
使用 $this->registerJsFile('js.js')来引入js文件;
URL
创建url
use yii\helpers\Url;
Url::to(['xxx/xxx']);
//或
Yii::$app->urlManager->createUrl('xxx.xxx')
Url助手
//不带域名根目录//echo Url::base();
//带域名的根目录//echoUrl::base(true);
//不带域名的首页//echoUrl::home();
//带域名的首页//echoUrl::home(true);
//当前url //echoUrl::current();
URL模块间跳转
Url::to(['/index/index'])
控制器间跳转
return $this->redirect(['member/security']);
请求参数
$request = Yii::$app->request;
请求
$get = $request->get();
//等价于: $get = $_GET;
$id = $request->get('id');
//等价于: $id = isset($_GET['id']) ? $_GET['id'] : null;
$id = $request->get('id', 1);
//等价于: $id = isset($_GET['id']) ? $_GET['id'] : 1;$post = $request->post();
//等价于: $post = $_POST;$name = $request->post('name');
//等价于: $name = isset($_POST['name']) ? $_POST['name'] : null;
$name = $request->post('name', '');
//等价于: $name = isset($_POST['name']) ? $_POST['name'] : '';
请求方式
$request = Yii::$app->request;
if ($request->isAjax) { /*该请求是一个AJAX请求*/ }
if ($request->isGet) { /*请求方法是GET */ }
if ($request->isPost) { /*请求方法是POST */ }
if ($request->isPut) { /*请求方法是PUT */ }
请求类属性
Yii::$app->request->url;
//结果:/admin/index.php/product?id=100,此URL不包括host info部分。
Yii::$app->request->absoluteUrl;
//结果:http://www.phpxs.com/post/index.php/product?id=100,包含host infode的整个URL。
Yii::$app->request->hostInfo;
//结果:http://www.phpxs.com,只有host info部分。
Yii::$app->request->pathInfo;
//结果:/product, 这个是入口脚本之后,问号之前(查询字符串)的部分。
Yii::$app->request->queryString;
//结果:id=100,问号之后的部分。
Yii::$app->request->baseUrl;
//结果:/admin, host info之后, 入口脚本之前的部分。
Yii::$app->request->scriptUrl;
//结果:/admin/index.php,没有path info和查询字符串部分。
Yii::$app->request->serverName;
//结果:example.com, URL中的host name。
Yii::$app->request->serverPort;
//结果:80,这是web服务中使用的端口。
Yii::$app->request->userAgent;
//结果:返回User-Agent头
Yii::$app->request->contentType;
//结果:返回Content-Type头的值,Content-Type是请求体中MIME类型数据。
Yii::$app->request->acceptableContentTypes;
//结果:返回用户可接受的内容MIME类型。 返回的类型是按照他们的质量得分来排序的。得分最高的类型将被最先返回。
Yii::$app->request->acceptableLanguages;
//结果:返回用户可接受的语言。 返回的语言是按照他们的偏好层次来排序的。第一个参数代表最优先的语言。
Yii::$app->request->getPreferredLanguage();
//结果:这个方法通过yiiwebRequest::acceptableLanguages在你的应用中所支持的语言列表里进行比较筛选,返回最适合的语言。
客户端信息
Yii::$app->request->userHost;
Yii::$app->request->userIP;
HTTP头部
$headers = Yii::$app->response->headers;
$headers->add('Pragma', 'no-cache');
//增加一个Pragma头,已存在的Pragma头不会被覆盖。
$headers->set('Pragma', 'no-cache');
//设置一个Pragma头.任何已存在的Pragma头都会被丢弃
$values = $headers->remove('Pragma');
//删除Pragma头并返回删除的Pragma头的值到数组
文件下载
yiiwebResponse::sendFile();
//发送一个已存在的文件到客户端
yiiwebResponse::sendContentAsFile();
//发送一个文本字符串作为文件到客户端
yiiwebResponse::sendStreamAsFile();
//发送一个已存在的文件流作为文件到客户端
public function actionDownload(){
return Yii::$app->response->sendFile('path/to/file.txt');
}
301跳转
Yii::$app->response->redirect('http://example.com/new', 301)->send();
状态码
Yii::$app->response->statusCode = 200;
表单用法(文本库)
<?php
/* @var $this yii\web\View */
/* @var $name string */
/* @var $message string */
/* @var $exception Exception */
use yii\helpers\Html;
use yii\bootstrap\ActiveForm;
?>
<?php $form = ActiveForm::begin(['id' => 'form-signup']); ?>
//文本框的标题
<?= $form->field($model, 'test1')->label('文本框的标题') ?>
//文本框下方的提示
<?= $form->field($model, 'test2')->hint('测试hint'); ?>
//input(type) type的类型有 text password等
<?= $form->field($model, 'test3')->input('text')?>
//简单文本框
<?= $form->field($model, 'test3')->textInput(['maxlength' => true])?>
//隐藏文本框
<?= $form->field($model, 'test3')->hiddenInput() ?>
//密码文本框,应用于登录的密码输入框
<?= $form->field($model, 'test3')->passwordInput() ?>
//文本域 应用于输入内容较多比如文章简介等 rows=>3 表示文本域高为3
<?= $form->field($model, 'test3')->textarea(['rows'=>'3']) ?>
//文件上传
<?= $form->field($model, 'test3')->fileInput() ?>
//勾选框
<?= $form->field($model, 'test3')->radio() ?>
//多选框
<?= $form->field($model, 'test3')->checkbox() ?>
//listbox
<?= $form->field($model, 'test3')->listBox(['0'=>'box1','1'=>'box2']) ?>
//多谢框列表,常用
<?= $form->field($model, 'test3')->checkboxList(['0'=>'box1','1'=>'box2']) ?>
//单选框列表,常用
<?= $form->field($model, 'test3')->radioList(['0'=>'radio1','1'=>'radio2'])?>
//下拉框列表
<?= $form->field($model, 'test3')->dropDownList(
['1'=>'下拉选项1','2'=>'下拉选项2'],
['prompt' => '请选择']
) ?>
//插件组件应用,比如yii2编辑器插件,图片上传插件
<?= $form->field($model,'test3')->widget(yii\captcha\Captcha::className())?>
<div class="form-group">
<?= Html::submitButton('按钮', ['class' => 'btn btn-primary', 'name' => 'signup-button']) ?>
</div>
<?php ActiveForm::end(); ?>
后台index页面显示图片:
[
'attribute' => 'headimgurl',
'format' => 'raw',
'value' => function ($data) {
$image = $data->headimgurl;
$imageHtml = Html::img($image, ['height' => '30']);
return $data->headimgurl ? Html::a($imageHtml, $image, ['data' => ['lightbox' => 'image-' . $data->user_id, 'title' => Html::encode($data->user_name)]]) : '';
},
],
控制器方法
1 .重定向 $this->redirect([‘test/index’])
2 .回到首页 $this->goHome()
3 .返回 $this->goBack()
4 .刷新当前页面 $this->refresh()
5 .渲染视图 $this->render(视图,注入视图数组数据)
6 .渲染没有layout的视图 $this->renderPartial(视图,注入视图数组数据)
7 .响应Ajax请求,有layout的视图 $this->renderAjax(视图,注入视图数组数据)
修改Test控制器的index操作
Request对象属性和方法
1.request对象\Yii::$app->request
2.判断Ajax请求\Yii::$app->request->isAjax
3.判断POST请求\Yii::$app->request->isPost
4.获取浏览器信息\Yii::$app->request->userAgent
5.获取客户端IP \Yii::$app->request->userIp
6.读取所有get数据\Yii::$app->request->get()
7.读取单个get数据\Yii::$app->request->get('r')
8.读取所有post数据\Yii::$app->request->post()
9.读取单个post数据\Yii::$app->request->get('post')
10.获取不包含host info的url部分\yii::$app->request->url
11.获取整个URL \Yii::$app->request->absoluteUrl
12.获取host info部分\Yii::$app->request->hostInfo;
13.入口脚本之后查询字符串之前\Yii::$app->request->pathInfo
14.查询字符串\Yii::$app->request->queryString
15.host info之后,入口脚本之前部分\Yii::$app->request->baseUrl;
设置cookie/seccion
Cookie
Yii2的cookie主要通过yii\web\Request和yii\web\Response来操作的。
通过\Yii::app->response->getCookies()->add($cookie)来添加cookie。
通过\Yii::app->request->cookies读取cookie
(一)、添加一个cookie
方法一:
$cookie = new \yii\web\Cookie();
$cookie->name = 'name'; //cookie名
$cookie->value = 'value'; //cookie值
$cookie->expire = time() * 3600; //过期时间
$cookie->httpOnly = true; //是否只读
\Yii::$app->response->getCookies()->add($cookie);
方法二:
$cookie = new \yii\web\Cookie([
'name' => 'name',
'value' => 'value',
'expire' => time() + 18000,
'httpOnly' => true
]);
\Yii::$app->response->getCookies()->add($cookie);
(二)、读取一个Cookie
$cookie = \Yii::$app->request->cookies;
$cookie->has('name');//判断cookie是否存在
$cookie->get('name');//get()方法读取cookie
$cookie->getValue('name');//getValue()方法读取cookie
$cookie->count();//获取cookie个数
$cookie->getCount();//获取cookie个数
(三)、删除一个Cookie
$name = \Yii::$app->request->cookies->get('name');
\Yii::$app->response->getCookies()->remove($name);
(四)、删除全部Cookie
\Yii::$app->response->getCookies()->removeAll();
Session
yii2的session通过yii\web\Session实例的session应用组件来访问。
$session = \Yii::$app->session;
(一)、添加一个session
$session->set('name_string','value');
$session->set('name_array',[1,2,3]);
(二)、读取一个session
$session->get('name_string');
$session->get('name_array');
(三)、删除一个session
$session->remove('name_array');
(四)、删除所有session
$session->removeAll();
模型的rules规则
常用验证规则:
1.【safe 不验证规则】
//['字段','safe']
//[['字段1','字段2',……],'safe']
2.【required 不能为空,必须验证】
//['字段','required','message' => '提示信息']
//[['字段1','字段2',……],'required','message' => '提示信息']
3.【compare 对比验证】
//['字段','compare','compareValue'=>'对比的值','message' => '提示信息']
//['字段','compare','compareAttribute'=>'对比的字段','message' => '提示信息']
4.【double 双精度数字验证】
//['字段','double','min'=>'最小值','max' => '最大值','tooSmall'=>'小于最小值提示','tooBig'=>'大于最大值提示','message'=>'提示信息']
5.【email 邮箱规则验证】
//['字段','email','message' => '提示信息']
6.【in 范围验证】
//['字段','in','range'=>['1','2','3',……],'message' => '提示信息']
7.【integer 整型数字验证】
//['字段','integer','message' => '提示信息']
8.【match 正则验证】
//['字段','match','parttern'=>'#正则#','message' => '提示信息']
9.【string 字符串验证】
//['字段','string','min'=>'最小长度','max' => '最大长度','tooShort'=>'小于最小长度提示','tooLong'=>'大于最大长度提示','message'=>'提示信息']
10.【unique 唯一验证】
//['字段','unique','message' => '提示信息']
11.【captcha 验证码验证】
//['字段','captcha','captchaAction',=>'login/captcha','message' => '提示信息']
12.自定义验证
//['字段','自定义方法']
//可通过在自定义方法里调用addError()来定义错误
例:
['username',function($attribute,$params){
if(满足条件){
$this->addError($attribute,'提示信息');
}
},'params'=>['message'=>'dd']]
13.向数据库传送int类型的时间戳格式转换
['create_time' , 'filter', 'filter' => function(){
return strtotime($this->create_time);
}],
渲染布局
Render 这个方法可以渲染布局;
Renderpartial 这个方法不会渲染布局;
方案1:控制器内成员变量
public $layout = false; //不使用布局
public $layout = "main"; //设置使用的布局文件
方案2:控制器成员方法内
$this->layout = false; //不使用布局
$this->layout = "main"; //设置使用的布局文件
方案3:视图中选择布局
$this->context->layout = false; //不使用布局
$this->context->layout = 'main'; //设置使用的布局文件
$this->layout='@app/views/layouts/main2.php';
小部件
常用部件
DetailView::widget——yii\widgets\DetailView::$model显示的是一条数据的详情
ActiveForm::begin——yii\widgets\ActiveForm生成一个登录表单
ListView::widget——yii\widgets\ListView从数据提供者显示数据
GridView::widget—— yii\grid\GridView: 从数据提供者获取数据
加密与解密
$data 是你要加密的内容,
$secretKey 是你自己设置的密码,
$encryptedData = Yii::$app->getSecurity()->encryptByPassword($data, $secretKey);
随后,当用户需要读取数据时:
$encryptedData 是你要解密的内容
$secretKey 是你自己设置加密时的密码
$data = Yii::$app->getSecurity()->decryptByPassword($encryptedData, $secretKey);
rbac授权
http://www.weixistyle.com/yii2/newclipo.php
Common\config\main.php
‘authManager’=>[
‘class’=>’yii\rbac\Dbmanager’,
],
…………
下拉菜单
提交表单下拉:
第一种:
<?= $form->field($model, 'test3')->dropDownList(
['1'=>'下拉选项1','2'=>'下拉选项2'],
['prompt' => '请选择']
) ?>
……………………………………………………………………………………………………………
<?= $form->field($model, 'status')->dropDownList($allStatus,
['prompt' => '请选择']);?>
第二种:
$psobjs=Poststatus::find()->all();
$allStatus=ArrayHelper::map($psobjs,’id’,’name’);
第三种:
$psArray=Yii::$app->db->
createCommand(‘select id,name from poststatus’)
->queryAll();
$allstatus=ArrayHelper::map($psarray,’id’,’name’);
第四种:
$allstatus=(new\yii\db\Query())
->select([‘name’,’id’])
->form(‘poststatus’)
->indexBy(‘id’)//把value取出为key
->column();
第五种:
Allstatus=Poststatus::find()
->selsct(‘name’,’id’)
->orderBy(‘position’)
->indexBy(‘id’)
->column();
第六种:
html:
<?= $form->field($model, 'activity_id')->dropDownList(\common\models\SmActivityUser::Activityuser()) ?>
models:
public static function Activityuser()
{
$data = SmActivity::getALL();
$zdara[]='请选择';
foreach ($data as $v){ $zdara[$v['activity_id']] = $v['name']; }return $zdara;}
SmActivity:
public static function getAll(){
return self::find()->all();
}
http://www.manks.top/yii2-gridview-dropdown-search.html
http://www.manks.top/yii2-dropdown-search.html
显示数据表单
在控制器里定义状态显示 用中文代替数字
constSTATUS_COD=0;
constSTATUS_UNPAID=11;
constSTATUS_PAYING=30;
constSTATUS_PAID=40;
添加方法
public static functiongetStatusLabels($id=null)
{
$data= [
self::STATUS_COD=> Yii::t('app','STATUS_COD'),
self::STATUS_UNPAID=> Yii::t('app','STATUS_UNPAID'),
self::STATUS_PAYING=> Yii::t('app','STATUS_PAYING'),
self::STATUS_PAID=> Yii::t('app','STATUS_PAID'),
];
if($id!==null&&isset($data[$id])) {
return$data[$id];
}else{
return$data;
}
}
在视图里
'width'=>'110px',
'value'=>function($model) {
returnEcmorder::getStatusLabels($model->status);
},
'filter'=>Html::activeDropDownList(
$searchModel,
'status',
Ecmorder::getStatusLabels(),
['class'=>'form-control','prompt'=> Yii::t('app','PROMPT_STATUS')]
),
表单修饰
时间戳查询
如果加插件在视图里加:
[
'attribute' => 'add_time',
'width'=>'200px',
'vAlign'=>'middle',
'headerOptions' => ['class' => 'col-md-2'],
'filter' => DatePicker::widget([
'model' => $searchModel,
'type' => DatePicker::TYPE_COMPONENT_APPEND,
'attribute' => 'add_time',
'options' => ['class' => 'input-sm'],
'pluginOptions' => [
'autoclose' => true,
'format' => 'yyyy-mm-dd'
]
]),
'format' => ['date', 'php:Y-m-d H:i:s'],
],
查询模型:
在rules add_time里面把integer改到safe
if ($this->add_time) {
$add_time = strtotime($this->add_time);
$add_timeEnd = $add_time + 24*3600;
$query->andWhere("add_time >= {$add_time} AND add_time <= {$add_timeEnd}");
}
加省略符号:
在视图上加
或者
在模型文件里加
在试图下加入
‘value’=’beginning’,
加搜索:
右上角退出
数组助手array helper
Getvalue:获取值 $value=arrayhelper::getvalue($array,’foo.bar.name’);
Getcolumn:获取列 $ids=arrayhelper::getcolumn($data,’id’);
Map:建立映射表 $result=arrayhelper::map($array,’id’,’name’);
Merge:合并数组 $result=arrayhelper::merge($array1,$array2);
Toarray:对象转换为数组 $data=arrayhelper::toarray($posts,[…])
yii2数据列表插件-gridview
需要添加一项 'export' => false, 即可,原先的gridview无需改动。
http://www.manks.top/yii2-gridview.html
1.在例头添加排序,在cloumns中加入以下代码
['class' => 'yii\grid\SerialColumn']
2.列表勾选框,在cloumns中加入以下代码
['class' => 'yii\grid\CheckboxColumn'],
3.列数据快速格式化:时间戳转化为时间格式显示
'created_at:datetime',
4.显示关联表数据:前提是在model中有关联关系,例如:getAuthor()
'author.name', //获取关联表author的name的值
5.列表中显示图片:显示一张50*100的图片,label_img为图片地址
'label_img'=>[
'label' => '标签图',
'format' => [
'image',
[
'height' =>50,
'width' => 100
]
],
'value' => function($model){
return $model->label_img;
}
],
6.显示状态,且带过滤
[
'attribute' => 'is_valid',
'label' => '发布状态',
'value' => function($model) {
return $model->is_valid == 0 ? '未发布' : '发布';
},
'filter' => [
0 => '未发布',
1 => '发布'
]
],
7.显示带html标签的例值:正常情况下是过滤html标签的
[
'attribute' => 'content',
'format' => 'raw',
'value' => function ($model) {
return $model->content;
},
],
8.自定义按钮:{view} {update} {delete} 为默认,可以不填显示默认,也可以覆盖重新定义
[
'class' => 'yii\grid\ActionColumn',
'template' => '{test} {view} {update} {delete}',
'header' => '操作',
'buttons' => [
'test' => function ($url, $model, $key) {
return Html::a('测试按钮', $url,['data-method' => 'post','data-pjax'=>'0'] );
},
'delete'=> function ($url, $model, $key){
return Html::a('删除', ['delete', 'id'=>$model->id],[
'data-method'=>'post', //POST传值
'data-confirm' => '确定删除该项?', //添加确认框
] ) ;
}
],
],
增减按钮
<?= Html::a('创建商品', ['create'], ['class' => 'btn btn-success']) ?>
<?= Html::a('批量删除', ['sanger'], ['class' => 'btn btn-danger']) ?>
删除:
['class' => 'yii\grid\CheckboxColumn'],
增删查改:
['class' => 'yii\grid\ActionColumn'],
序号:
['class' => 'yii\grid\SerialColumn'],
分页和排序:
在控制器**search‘query’=>$query下增加
//定义哪些可以排序
Yii时间转换
[
'attribute' => 'created_at',
'format' => ['date', 'php:Y-m-d H:i:s'],
设置宽度
'contentOptions'=>['width'=>'110px'],
],
链接可点击跳转
[
'attribute' => 'order_id',
'value' => function ($model) {
return Html::a($model->order_id, "/order?id={$model->order_id}", ['target' => '_blank']);
},
'format' => 'raw',
],
数据列有链接
[
'attribute' => 'title',
'value' => function ($model, $key, $index, $column) {
return Html::a($model->title,
['article/view', 'id' => $key]);
},
'format' => 'raw',
],
我们举一个简单的案例
条件:有一个get形参数type
需求:仅且type的值等于1的时候,列name才显示,否则该列不显示
代码实现如下:
[
"attribute" =>"name",
"value" =>$model->name,
"visible" => intval(Yii::$app->request->get("type")) == 1,
],
本地图片显示:
[
'attribute' => 'qr_code',
'format' => 'raw',
'value' => function ($data) {
$image = '../..' . $data->qr_code;
$imageHtml = Html::img($image, ['height' => '30']);
return $data->qr_code ? Html::a($imageHtml, $image, ['data' => ['lightbox' => 'image-' . $data->activity_id, 'title' => Html::encode($data->name)]]) : '';
},
],
控制器接收json:
common\config\main.php
'request' => [
'parsers' => [
'application/json' => 'yii\web\JsonParser',
'text/json' => 'yii\web\JsonParser',
],
],
列表:
<?= Html::dropDownList('shipping_id', '',ArrayHelper::map(\common\models\SmShipping::GetAll(), 'shipping_id', 'shipping_name'),['class'=>'form-control w130 float_left']) ?>
添加事件添加时间:
public function beforeSave($insert)
{
if (parent::beforeSave($insert)) {
if ($this->isNewRecord){
!$this->add_time && $this->add_time = time();
}else{
// !$this->update_time && $this->update_time = time();
}
return true;
} else
return false;
}