Use Yii2 Gridview SerialColumn as rank - yii2

How do I use the values of the Serial Column as ranking?
Example:
If the value is 1, I show gold.png,
If value is 2, I show silver.png,
If value is 3, I show bronze.png,
I did so but gave not sure:
'columns' => [
[
'class' => 'yii\grid\SerialColumn',
'content' => function($model, $key, $index, $column) {
if ($index == 1) {
return Html::img(Yii::$app->request->BaseUrl.'/images/medal-gold-icon.png');
}elseif ($index == 2) {
return Html::img(Yii::$app->request->BaseUrl.'/images/medal-silver-icon.png');
}elseif ($index == 3) {
return Html::img(Yii::$app->request->BaseUrl.'/images/medal-bronze-icon.png');
}else {
return Html::img(Yii::$app->request->BaseUrl.'/images/no-medal-icon.png');
}
}],

Why don't you use a custom column?
'columns' => [
[
'format' => 'raw',
'header' => 'Rank',
'value' => function($model, $key, $index, $column) {
if ($index == 1) {
return Html::img(Yii::$app->request->BaseUrl.'/images/medal-gold-icon.png');
}elseif ($index == 2) {
return Html::img(Yii::$app->request->BaseUrl.'/images/medal-silver-icon.png');
}elseif ($index == 3) {
return Html::img(Yii::$app->request->BaseUrl.'/images/medal-bronze-icon.png');
}else {
return Html::img(Yii::$app->request->BaseUrl.'/images/no-medal-icon.png');
}
}],

Related

how do I display the same data and aggregate it in one line in yii2?

MODEL
public function getJumlah()
{
return $this->hasMany(AssetMaster::className(), ['id_asset_received' => 'received_date'])
->leftJoin('asset_received','asset_received.id_asset_received = asset_master.id_asset_master')
->groupBy('received_date')
->count();
}
VIEW
<?= GridView::widget(
[
'behaviors' => [
[
'class' => '\dosamigos\grid\behaviors\GroupColumnsBehavior',
'extraRowColumns' => ['assetMaster.asset_name'],
'extraRowValue' => function($model, $key, $index, $totals) {
return '<span class="label label-warning">' . $model['received_year'] . '</span>';
},
'mergeColumns' => ['assetMaster.asset_name','received_year']
]
],
'columns' => [
'assetMaster.asset_name',
received_date',
'received_year',
'Jumlah'
],
'dataProvider' => $dataProvider,
'layout' => "\n{items}\n{pager}"
]
);
?> '
i want sum "nama barang " every search i use , for now "jumlah" is the result of COUNT
and make it into just one line, is there anyone who can help

Yii2 Gridfilter date range picker

I have developed application in yii2 and for filter in grid view i had used Kartik date-range picker extension.
I have faced following problem.
When i select different date for start and end date then it will worked.
e.g start date 5 and end date 10
When i select next day same date for start and end date then it will worked.
e.g start date 6 and end date 6
When i select today's date for start and end date then it will not worked.
e.g start date 5 and end date 5
Sample code.
<?php
$gridColumns = [
[
'class' => 'kartik\grid\SerialColumn'
],
[
'label' => Yii::t('app', "Created At"),
'attribute' => 'created_at',
'value' => function ($model) {
if (extension_loaded('intl')) {
return $model->created_at;
} else {
return $model->created_at;
}
},
'filter' => DateRangePicker::widget(
[
'model' => $searchModel,
'attribute' => 'created_at',
'convertFormat' => true,
'presetDropdown' => false,
'pluginOptions' => [
'locale' => [
'format' => 'Y-m-d'
]
]
]
)
],
[
'attribute' => 'branch_id',
'value' => 'branch.name',
'filter' => Html::activeDropDownList(
$searchModel,
'branch_id',
ArrayHelper::map(Branch::find()->asArray()->all(), 'id', 'name'),
['class' => 'form-control', 'prompt' => 'Select Branch']
)
],
[
'attribute' => 'user_id',
'value' => 'user.firstname',
'filter' => Html::activeDropDownList(
$searchModel,
'user_id',
ArrayHelper::map(User::find()->asArray()->all(), 'id', 'firstname'),
['class' => 'form-control', 'prompt' => 'Select User']
)
],
[
'attribute' => 'order_status',
'format' => 'html',
'filter' => ["0" => "Completed", "1" => "Refund", "2" => "Cancel"],
'value' => function ($model) {
if ($model->order_status == '1') {
return '<span class="label bg-red">Refund</span>';
} else if ($model->order_status == '2') {
return '<span class="label bg-yellow">Cancel</span>';
} else {
return '<span class="label bg-blue">Completed</span>';
}
}
],
[
'attribute' => 'created_from',
'format' => 'html',
'value' => function ($model) {
if ($model->created_from == '1') {
return '<span class="">WEB<small>';
} else if ($model->created_from == '2') {
return '<span class="">IOS<small>';
} else if ($model->created_from == '3') { //MARKAS
return '<span class="">ANDROID<small>';
}
}
],
[
'attribute' => 'pax',
'format' => 'html',
'value' => function ($model) {
$setting = common\constants\EstablishmentConfiguration::activeSetting();
$type = '';
$paxFlag = '0';
if (!empty($setting)) {
$type = $setting->establishment_type;
$paxFlag = $setting->enable_pax;
}
if ($type == 'restaurant' && $paxFlag == '1') {
return $model->pax;
} else {
return '--';
}
}
],
//'pax',
'sub_total',
'discount',
'tax',
'grand_total',
[
'class' => 'yii\grid\ActionColumn',
'header' => Yii::t('app', 'Action'),
'template' => '{view} {movetofack}',
'contentOptions' => ['style' => 'width:10%'],
'buttons' => [
'view' => function ($url, $model) {
return Html::a(
'<span class="glyphicon glyphicon-eye-open"></span>',
['view', 'id' => $model->id],
[
'class' => 'btn btn-xs btn-warning',
'title' => 'View',
'data-skin' => 'skin-warning'
]
);
},
'movetofack' => function ($url, $model) {
return Html::a(
'<span class=" fa fa-trash"></span>',
[
'movettotrash', 'id' => $model->id
],
[
'class' => 'btn btn-xs btn-warning',
'title' => 'Fack Record',
'data-skin' => 'skin-warning',
'data' => [
'confirm' => Yii::t('app/msg', 'Are you sure this is fake record? would you like to move to trash this order?'),
'method' => 'post'
]
]
);
}
]
]
];

Hide row in yii2 gridview depending on actioncolumn

I have a gridview in which I have custom actioncolumn according to user authorization and other conditions. Due to this conditions, in few rows, there are no action item button for few rows. I want to hide these rows.
I can hide the row on condition by rowoption. But I want to know how can I hide it according to the action item button.
Following is the index view page -
<?php
use yii\helpers\Html;
use kartik\grid\GridView;
use yii\helpers\ArrayHelper;
use frontend\modules\workpermit\models\Workpermit;
use frontend\modules\workpermit\models\Extension;
use frontend\modules\workpermit\models\WpindexSearch;
use frontend\modules\workpermit\models\Aclpath;
use yii\widgets\Pjax;
/* #var $this yii\web\View */
/* #var $searchModel frontend\modules\workpermit\models\WorkpermitSearch */
/* #var $dataProvider yii\data\ActiveDataProvider */
$this->title = 'All Permits';
$this->params['breadcrumbs'][] = $this->title;
?>
<div class="workpermit-index">
<h1><?= Html::encode($this->title) ?></h1>
<?php // echo $this->render('_search', ['model' => $searchModel]); ?>
<p>
<?= Html::a('Home', ['/site/index'], ['class' => 'btn btn-success']) ?>
<?= Html::a('Refresh', ['/workpermit/workpermit/awsup'], ['class' => 'btn btn-primary']) ?>
</p>
<?php Pjax::begin(['id' => 'allpermitview']); ?>
<?= GridView::widget([
'dataProvider' => $dataProvider,
'filterModel' => $searchModel,
'rowOptions' => function($model){
if($model->wp_type == 'Excavation Permit'){
return ['class' => 'hide'];
}
},
'options' => [
'style'=>'overflow: auto; word-wrap: break-word;'
],
'columns' => [
//['class' => 'yii\grid\SerialColumn'],
[
'class' => 'kartik\grid\ExpandRowColumn',
'value' => function($model, $key, $index, $column){
return GridView::ROW_COLLAPSED;
},
'detail' => function($model, $key, $index, $column){
$model = Workpermit::find()->where(['wp_no' => $model->wp_no])->one();
$searchModel = new WpindexSearch();
$aclfileuploadpaths = Aclpath::find()->select('aclp_path')->where(['aclp_wpno'=>$model->wp_no])->column();
// $searchModel->wp_no = $model->wp_no;
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
$id = $model->wp_no;
if($model->wp_type == 'Safe Work Permit'){
return Yii::$app->controller->renderPartial('_approvalstatussafe', [
'id' => $id,
'model' => $model,
'searchModel' => $searchModel,
'dataProvider' => $dataProvider,
//'from_date' => $from_date, 'to_date'=>$to_date
]);
}
elseif($model->wp_type == 'Hot Work Permit'){
return Yii::$app->controller->renderPartial('_approvalstatushot', [
'id' => $id,
'model' => $model,
'searchModel' => $searchModel,
'dataProvider' => $dataProvider,
//'from_date' => $from_date, 'to_date'=>$to_date
]);
}
elseif($model->wp_type == 'Excavation Permit'){
return Yii::$app->controller->renderPartial('_approvalstatusexcav', [
'id' => $id,
'model' => $model,
'searchModel' => $searchModel,
'dataProvider' => $dataProvider,
//'from_date' => $from_date, 'to_date'=>$to_date
]);
}
elseif($model->wp_type == 'Confined Space Permit'){
return Yii::$app->controller->renderPartial('_approvalstatusconfined', [
'id' => $id,
'model' => $model,
'searchModel' => $searchModel,
'dataProvider' => $dataProvider,
//'from_date' => $from_date, 'to_date'=>$to_date
]);
}
},
],
'wp_no',
[
'label' => 'WP Type',
'attribute' => 'permittyp',
'value' => 'permittype.wpt_short',
'filterType'=>GridView::FILTER_SELECT2,
'filter'=>ArrayHelper::map(Workpermit::find()->asArray()->all(), 'wp_type', 'wp_type'),
'filterWidgetOptions'=>[
'pluginOptions'=>['allowClear'=>true],
],
'filterInputOptions'=>['placeholder'=>'Type'],
],
[
'label' => 'Status',
//'attribute'=>'status',
'attribute'=>'wp_status',
'filterType'=>GridView::FILTER_SELECT2,
'filter'=>ArrayHelper::map(Workpermit::Find()->asArray()->all(), 'wp_status', 'wp_status'),
'filterWidgetOptions'=>[
'pluginOptions'=>['allowClear'=>true],
],
'filterInputOptions'=>['placeholder'=>'Permit Status'],
'contentOptions' => function($model, $key, $index, $column){
if($model->wp_status == 'Available'){
return['style' => 'background-color:red'];
}elseif($model->wp_status == 'Approved'){
return['style' => 'background-color:green'];
}elseif($model->wp_status == 'Work in Progress'){
return['style' => 'background-color:yellow'];
}elseif($model->wp_status == 'Completed'){
return['style' => 'background-color:blue'];
}
}
],
'wp_date',
//'wp_time',
'wp_validto',
[
'attribute'=>'wp_plant',
'filterType'=>GridView::FILTER_SELECT2,
'filter'=>ArrayHelper::map(Workpermit::find()->asArray()->all(), 'wp_plant', 'wp_plant'),
'filterWidgetOptions'=>[
'pluginOptions'=>['allowClear'=>true],
],
'filterInputOptions'=>['placeholder'=>'Plant'],
],
[
'attribute'=>'wp_area',
'filterType'=>GridView::FILTER_SELECT2,
'filter'=>ArrayHelper::map(Workpermit::find()->asArray()->all(), 'wp_area', 'wp_area'),
'filterWidgetOptions'=>[
'pluginOptions'=>['allowClear'=>true],
],
'filterInputOptions'=>['placeholder'=>'Area'],
],
//'wp_area',
'wp_jobdesc',
[
'label' => 'View',
'content' => function ($model, $key, $index, $column) {
return Html::a('<span class="glyphicon glyphicon-eye-open"></span>', ['viewall', 'id' => $model->wp_no])
. ' ' .Html::a('<span class="glyphicon glyphicon-print"></span>', ['/workpermit/workpermit/printpermit', 'id' => $model->wp_no]);
}
],
[ 'label' => 'Action',
'content' => function ($model, $key, $index, $column) {
//The Supervisor Conditions//
if ($model->wp_status == 'Assigned' && Yii::$app->user->can('s_jsapproval')) {
return Html::a('<span class="glyphicon glyphicon-pencil"></span>', ['updateapproval', 'id' => $model->wp_no]);
}
elseif ($model->wp_type == 'Safe Work Permit' && $model->wp_apoapproval == 'Approved' && $model->wp_spsapproval == 'Approved' && $model->wp_officerapproval == 'Approved' && Yii::$app->user->can('s_jsapproval') && $model->wp_jc != 'Completed' && ($model->wp_status == 'Approved' || $model->wp_status == 'Work in Progress' || $model->wp_status == 'Assigned')) {
return Html::a('<span class="glyphicon glyphicon-pencil"></span>', ['updateassignwp', 'id' => $model->wp_no]);
}
elseif ($model->wp_type == 'Hot Work Permit' && $model->wp_apoapproval == 'Approved' && $model->wp_spsapproval == 'Approved' && $model->wp_officerapproval == 'Approved' && $model->wp_emsuper == 'Approved' && $model->wp_plsuper == 'Approved' && Yii::$app->user->can('s_assignwp') && ($model->wp_status == 'Approved' || $model->wp_status == 'Work in Progress')) {
return Html::a('<span class="glyphicon glyphicon-pencil"></span>', ['updateassignwp', 'id' => $model->wp_no]);
}
elseif ($model->wp_type == 'Confined Space Permit' && ($model->wp_status == 'Assigned' || $model->wp_status == 'Work in Progress' || $model->wp_status == 'Approved') && Yii::$app->user->can('s_assignwp')){
return Html::a('<span class="glyphicon glyphicon-pencil"></span>', ['updateassignwp', 'id' => $model->wp_no]);
}
}
],
],
]); ?>
<?php Pjax::end(); ?>
</div>
<?php
/* start getting the another permit Type */
$script = <<< JS
$('#workpermit-wp_spost13').on('click',function(e){
$.pjax.reload({container: "#allpermitview"});
});
JS;
$this->registerJs($script);
/* end getting the another permit Type */
?>
A couple of options for you:
Add a Where Condition to you Search Query
Note: You could also apply optional filters in your search model.
class SomeController extends Controller
{
public function actionIndex()
{
$this->layout = "#app/views/layouts/main-app";
$searchModel = new WorkpermitSearch ();
$queryParams = Yii::$app->request->queryParams;
$dataProvider = $searchModel->search($queryParams);
$dataProvider->query->andWhere(['or',
['wp_type' => 'Safe Work Permit')],
['wp_type'=> 'Hot Work Permit'],
])
->orderBy(['wp_type' => SORT_DESC ]);
return $this->render('index', [
'searchModel' => $searchModel,
'dataProvider' => $dataProvider,
]);
}
Apply a Hide Class in Gridview at rowOptions
<?= GridView::widget([
'dataProvider' => $dataProvider,
'filterModel' => $searchModel,
//'emptyCell'=>'-',
//'formatter' => ['class' => 'yii\i18n\Formatter', 'nullDisplay' => ''], //Hide "not set" fields.
//'tableOptions' => ['class' => 'table'],
//'options' => ['style' => 'font-size: 1.2em;'],
'rowOptions' => function($model, $key, $index, $grid){
if ($model->wp_type == 'Safe Work Permit'){
return ['style' => 'visibility:collapse;'];
} else {
return ['style' => 'visibility:visible;'];
}
},
...

Yii2 Select2 multiple with ajax: Illegal offset type

I use Yii2 and widget Select2. I want onkeyup to search products from table "Products" with options for multiple select, because i must save result in second table "rel_products". I do know why it return error : "Illegal offset type"
Here is model:
public $products = array(); =>because i write result in second table
here is view:
$url = \yii\helpers\Url::to(['/product/prodlist']);
echo $form->field($model, 'products')->widget(Select2::classname(), [
'initValueText' => 'Search for a city ...', // set the initial display text
'model' => $model,
'attribute' => 'products',
'theme' => 'bootstrap',
'options' => ['placeholder' => 'Search for a city ...'],
'pluginOptions' => [
'allowClear' => true,
'minimumInputLength' => 3,
'ajax' => [
'url' => $url,
'dataType' => 'json',
'data' => new JsExpression('function(params) { return {q:params.term}; }')
],
'escapeMarkup' => new JsExpression('function (markup) { return markup; }'),
'templateResult' => new JsExpression('function(product) { return product.text; }'),
'templateSelection' => new JsExpression('function (product) { return product.text; }'),
],
]);
Here is Controller:
public function actionProdlist($q = null, $id = null) {
\Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
$out = ['results' => ['id' => '', 'text' => '']];
if (!is_null($q)) {
$query = new Query;
$query->select()
->from('product')
->joinWith('translation')
->where(['like', 'title', $q])
->limit(20);
$command = $query->createCommand();
$data = $command->queryAll();
$out['results'] = array_values($data);
}
elseif ($id > 0) {
$out['results'] = ['id' => $id, 'text' => Product::find($id)->title];
}
return $out;
}
change in model:
public $products; =>because i write result in second table

Put ActiveForm in Gridview Column Yii2

How can put an ActiveForm in a gridview column? The following is the code I made: I tried to render the page such that it includes the active form which I need.
'columns' => [
[ 'format' => 'html',
'value'=> function($data) { return Html::img($data->imageurl) . " <p class='feedback-username'>" . $data->username . "</p>"; },
'contentOptions'=>['style'=>'width: 30px; height: 30px'],
],
[ 'format' => 'raw',
'value' => function($model) { return "<p class='feedback'>". $model->KOMENTAR ."</p><br><p class='feedback-date'>". $model->TANGGAL ."</p><hr><div id='replay-". $model->ID_KOMENTAR."'><ul></ul></div>";},
],
[ 'format' => 'raw',
'contentOptions'=>['style'=>'width: 5px;'],
'value' => function($model) {
if($model->id == Yii::$app->user->identity->id) {
return Html::a('<i class="glyphicon glyphicon-share-alt"></i>',null,['id'=> 'replay-to-'. $model->ID_KOMENTAR ]).' '.
Html::a('<i class="glyphicon glyphicon-pencil"></i>', ['update', 'id' => $model->id]).' '.
Html::a('<i class="glyphicon glyphicon-trash"></i>', ['delete', 'id' => $model->id], ['data' => ['confirm' => 'Do you really want to delete this element?','method' => 'post']]);
}
return Html::a('<i class="glyphicon glyphicon-share-alt"></i>',['feedback', 'id' => $model->id],['id'=> 'replay-to-'. $model->ID_KOMENTAR ]);
},
],
[
'content' => $this->render('feedback_test'),
],
But I got this error:
PHP Warning – yii\base\ErrorException
call_user_func() expects parameter 1 to be a valid callback, function '
<div class="feedback-form">
<p>test</p>
</div>' not found or invalid function name
How do I include the active form in the grid view's column?
Try this.
[
'content' => function($model, $key, $index, $column) {
echo $this->render('feedback_test');
OR
echo $this->render('feedback_test', ['model' => $model]);
},
],
The above answer outputted the form above my grid. I wanted the form in one of my columns for every row of data. I ended up customizing an ActionColumn like this:
[
'class' => 'yii\grid\ActionColumn',
'template' => '{map}',
'contentOptions' => ['class' => 'text-center'],
'buttons' => [
'map' => function ($model) use ($m, $r) {
return $this->render('_form', ['model' => $m, 'req' => $model, 'ref' => $r]);
},
],
'urlCreator' => function ($action, $model) {
if ($action === 'map') {
return $model;
}
},
]