YII框架实现排序

YII框架实现排序

用YII2实现批量修改排序功能,如下图

YII框架实现排序

控制器:

/**
* Lists all CollectionAlbum models.
* @return mixed
*/
public function actionIndex($collectionId=0)
{
$collection = Collection::findOne($collectionId);
if(!$collection){
throw new NotFoundHttpException('The requested page does not exist.');
} $dataProvider = new ActiveDataProvider([
'query' => $collection->getAlbums(),
'sort' => [
'defaultOrder' => [
'sort'=>SORT_DESC,
'id' => SORT_DESC
]
],
]); if (Yii::$app->request->isPost) {
CollectionAlbum::saveSort(Yii::$app->request->post('ids'),Yii::$app->request->post('sorts'));
}
return $this->render('index', [
'dataProvider' => $dataProvider,
'collection'=>$collection,
]);
}

模型

    /**
*保存排序结果
* @param array $ids 图片ID组成的数组
* @param array $sorts 排序结果组成的数组
* */
public static function saveSort($ids,$sorts){
foreach($ids as $k=>$v){
$album=CollectionAlbum::findOne(intval($v));
$album->sort = $sorts[intval($k)];
$album->save(false);
}
}

视图

<?php

use yii\helpers\Html;
use yii\grid\GridView; /* @var $this yii\web\View */
/* @var $dataProvider yii\data\ActiveDataProvider */ $this->title = '藏品图集:'.$collection->title;
$this->params['breadcrumbs'][] = ['label' => '藏品', 'url' => ['collection/index']];
$this->params['breadcrumbs'][] = '藏品图集'; ?>
<div class="collection-album-index"> <p>
<?= Html::a('添加图片', ['create','collectionId'=>$collection->id], ['class' => 'btn btn-success']) ?>
</p>
<?= Html::beginForm(Yii::$app->request->hostInfo.Yii::$app->request->getUrl(),'post')?>
<?= GridView::widget([
'dataProvider' => $dataProvider, 'columns' => [
[
'header'=>'排序',
'class' => yii\grid\Column::className(),
'content'=>function ($model){
return Html::hiddenInput('ids[]',$model->id).Html::textInput('sorts[]',$model->sort,['style'=>'width:45px;','class'=>'form-control'
]);
}

],
[
'header'=>'图片',
'class' => yii\grid\Column::className(),
'content'=>function($model){
return Html::img($model->img_url.'?imageView2/1/w/100/h/100');
},
],
'summary',
'created_at:datetime',
[
'attribute'=>'status',
'value'=>function($model){
return $model->getStatusName();
},
],
['class' => 'yii\grid\ActionColumn','template'=>'{update} {delete}']
],
'tableOptions'=>['class' => 'table table-striped']
]); ?>
<?= Html::submitButton('更改排序',['class'=>'btn btn-primary'])?>
<?= Html::endForm()?>
</div>
上一篇:android 随手记 摄像头录像


下一篇:KeilC51高级编程