一些使用Yii2时遇到的问题解决方法记录

調用的控制器返回 json格式的數據即可,對json裡面的數據沒有要求

如在控制器中添加一個方法:

1
2
3
4
5
6
public function actionRemoveImage($id){
Yii::$app->response->format = yii\web\Response::FORMAT_JSON;
Yii::$app->response->data = [
'status' => true
];
}

参考: How add one more button to yii2-widget-fileinput?

  • yii2 下載文件

使用 yii2的sendfile方法

1
2
3
4
5
function actionDownload()
{
$imgFullPath = 'picture.jpg';
return Yii::$app->response->sendFile($imgFullPath);
}
  • yii2 實現類似 required_if 的功能

Yii2: Conditional Validator always returns required

  • number spinner 数值微调器

  • yii2 Select2 Widget 二級聯動

參考

  1. krajee Select2 Settings 裡面有 pluginEvents
  2. select2 plugin Add, select, or clear items select2 中添加元素和清空選項
  3. Yii2.0 实现三级联动 yii2的多級聯動參考
  • yii2 grid view show footer

girdview 中添加 'showFooter'=>true,, gridview中就會顯示table footer部分,在需要顯示的列中,添加 'footer'=> '',就會顯示對應的值

eg.

1
2
3
4
5
6
7
8
9
$total = 0;

foreach($dataProvider->models as $m) {
if(is_numeric($m->price)){
$total += $m->price;
}
}

$showFooter = $total > 0?true:false;
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
<?= GridView::widget([
'dataProvider' => $dataProvider,
'showFooter'=>$showFooter,
'columns' => [
'id',
'name',
[
'attribute' => 'price',
'value' => function($model){
return $model->price;
},
'footer' => number_format($total,2)
],
[
'header' => 'Action',
'class' => 'yii\grid\ActionColumn',
'template' => '{view} {update} {delete}',
'headerOptions' => ['width' => '80'],
],
],
]); ?>

参考: Gridview with sum in footer