yii2 GridView how to change column? - yii2

echo \yii\grid\GridView::widget(
[
/**
* Экземпляр класса, который реализует \yii\data\DataProviderInterface. В нашем случае ActiveDataProvider
*/
'dataProvider' => $dataProvider,
'columns' => [
'ip',
'date',
'request',
[
'attribute' => 'ip',
'value' => function ($data) {
return long2ip($data['ip']);
}
]
],
]
);
ip changes, but date and request disappear, how to fix it
ip changes, but date and request disappear, how to fix it

So, just change this part:
'columns' => [
[
'attribute' => 'ip',
'value' => function ($data) {
return long2ip($data['ip']);
}
]
'date',
'request',
],
you just duplication one elment of array, and now you can use it.

Related

Yii2: how to pass data column in actionColumn?

I have a GridView with two columns: country_name and an actionColumn with a button called Save.
The Save button is a hiperlink to, for example:
http://localhost/countries/view?country_name=Argentina
I don't know how to set Argentina to country_name because my view doesn't have a model. I only have data from the column country_name.
GridView::widget([
'dataProvider' => $dataProvider,
'columns' => [
'country_name',
[
'class' => 'yii\grid\ActionColumn',
'template' => '{save}',
'buttons' => [
'save' => function($model) {
return Html::a('Save', ['/countries/view', 'country_name' => $model['country_name']]); // Error: Illegal string offset 'country_name'
}
]
],
],
])
I am using this Yii2 help.
See ActionColumn:$buttons documentation - model is passed as second argument to button callback:
'buttons' => [
'save' => function($url, $model) {
return Html::a('Save', ['/countries/view', 'country_name' => $model['country_name']]);
}
]

Yii2 Custom filter Dropdown for gridview

I am trying to add a custom filter named Sort By Month in the grid view header here is an example of the previous version of the site which I am revamping see below image
I was looking into the layout option of the grid view and added a drop-down in the layout template before {items}
GridView::widget(
[
'dataProvider' => $dataProvider,
'filterModel' => $searchModel,
'layout' => '{summary}{errors}' . \kartik\widgets\Select2::widget(
[
'model' => $searchModel,
'attribute' => 'filter_month',
'theme' => \kartik\widgets\Select2::THEME_DEFAULT,
'data' => $searchModel->getFilterMonths(),
'pluginEvents' => [
"select2:select" => 'function() { $("#w2").submit();}',
// 'select2:select'=> new \yii\web\JsExpression("function(){console.log('here')}"),
],
'options' => [
'placeholder' => '--Select Month--',
],
'pluginOptions' => [
'allowClear' => true,
'width' => '160px',
],
]
) . '{items}{pager}',
'columns' => [
['class' => 'yii\grid\SerialColumn'],
'name',
'title',
'catalog',
'upc_code',
[
'attribute' => 'created_on',
'label' => 'Created On',
'filter' => \yii\jui\DatePicker::widget(['dateFormat' => 'yyyy-MM-dd', 'model' => $searchModel, 'attribute' => 'created_on']),
'format' => 'html',
],
[
'attribute' => 'status',
'label' => 'Status',
'format' => 'raw',
'value' => function ($data) {
switch ($data->status) {
case 0:
return "Being Edited (" . $data->created_on . ")";
break;
case 1:
return ($data->maxdate == '') ? 'Active' : 'Active';
break;
case 2:
return "Expired";
break;
}
},
],
['class' => 'yii\grid\ActionColumn'],
],
]
);
Now I want to submit the filters form when I select an option from the drop-down, but could not figure out how to attach the default filter submit event with the drop-down options so that it filters the results when I select any option in the drop-down.
For Custom filter you have used the perfect layout but you have to provide your custom field as a filterSelector.
"filterSelector" => "#". Html::getInputId($searchModel, 'AttributeName'),

Remove Dollar sign from Column value(Indian Currency) Yii2 kartik gridview

Below is the snapshot of my index page in Yii2 with Kartik Gridview widget;
Below is the gridview code for the same.
<?= GridView::widget([
'dataProvider' => $dataProvider,
//'filterModel' => $searchModel,
'columns' => [
[
'class' => 'kartik\grid\SerialColumn',
'contentOptions' => ['class' => 'kartik-sheet-style'],
'headerOptions' => ['class' => 'kartik-sheet-style'],
],
//'line_id',
'metal_name',
'item',
'unit_name',
'weight',
['attribute' => 'quantity',
'pageSummary' =>(true),
'value' => function ($model) {
if($model){
return $model->quantity;
}
}],
'rate_per_gram',
'making_charges',
[
'attribute' => 'total',
'format'=>'currency',
'pageSummary' =>(true),
'value' => function ($model) {
if($model){
return $model->total;
}
}
],
['class' => 'kartik\grid\ActionColumn'],
],
'responsive'=>true,
'hover'=>true,
'export'=>false,
'showPageSummary' => true,
]); ?>
I have tried lot of stuff to get plain number format with 2 decimals, but i could succeed in one.
How can I Format my Total column with Indian Currency, viz. Rs. 35670.00 or just 35670.00?
One way is to set currency directly:
[
'attribute' => 'total',
'format' => ['currency', 'INR'],
'pageSummary' => true,
],
PS. You don't need to set value key unless you want to replace it with something else in certain case.

Displaying yii2 filterboxes fails in a custom function column

I have a grid that i would like to filter but the filter boxes are not enabled in the column
This is the grid row
[
'attribute'=>' category',
'value'=>function($model){
switch ($model->category){
case 1:{
return "Normal truck";
}
case 2:{
return "Bulker truck";
}
}
},
'filter'=>array(1=>"Normal truck",2=>"Bulker truck"), //the dropdown filter
],
And this is my grid configuration
echo DynaGrid::widget([
'columns' => $columns,
'showPersonalize' => true,
//'allowThemeSetting'=> false,
'options' => ['id' => 'company_truck_grid'],
'gridOptions' => [
'options' => ['id' => 'company_grid_trcl_inside'],
'dataProvider' => $dataProvider,
'filterModel' => $searchModel, //filter is set
............
]
]);
This is whats being displayed
As you can see the category column has no dropdown filter and is disabled.. Where am i wrong..

TimestampBehavior is not working in Yii2

public function behaviors()
{
return [
'verbs' => [
'class' => VerbFilter::className(),
'actions' => [
'delete' => ['post'],
],
],
'access' => [
'class' => AccessControl::className(),
'only' => ['create', 'update', 'delete', 'view', 'index'],
'rules' => [
// allow authenticated users
[
'allow' => true,
'roles' => ['#'],
],
// everything else is denied by default
],
],
[
'class' => TimestampBehavior::className(),
'attributes' => [
ActiveRecord::EVENT_BEFORE_INSERT => ['create_time', 'update_time'],
ActiveRecord::EVENT_BEFORE_UPDATE => ['update_time'],
],
],
];
}
Above code is for my controller behavior function. While creating or updating, 'create_time' and 'update_time' fields are not getting updated by current time. Type of those fields are set to datetime. Please need your help.
You have to declare it in the behaviors method of your model.
To use TimestampBehavior, insert the following code to your ActiveRecord class
public function behaviors()
{
return [
'class' => TimestampBehavior::className(),
'attributes' => [
ActiveRecord::EVENT_BEFORE_INSERT => ['create_time', 'update_time'],
ActiveRecord::EVENT_BEFORE_UPDATE => ['update_time'],
],
];
}
Try this, it works for me:
use yii\db\Expression;
...
[
'class' => TimestampBehavior::className(),
'updatedAtAttribute' => 'update_time',
'value' => new Expression('NOW()'),
],
You can also use
'value' => date('Y-m-d H:i:s')
if you would like to use the PHP datetime.
I used new Expression('NOW()') to store current timestamp. But It does't store the date based on current timezone. Instead it stores based on server time.
I just used normal php date function to solve this.
eg :
use yii\behaviors\TimestampBehavior;
use yii\db\Expression;
public function behaviors()
{
return [
'timestamp' => [
'class' => 'yii\behaviors\TimestampBehavior',
'attributes' => [
ActiveRecord::EVENT_BEFORE_INSERT => ['created_at', 'updated_at'],
ActiveRecord::EVENT_BEFORE_UPDATE => ['updated_at'],
],
'value' => date('Y-m-d H:i:s'),
],
];
}
You must also add the value and use the class Expression
use yii\behaviors\TimestampBehavior;
use yii\db\Expression;
public function behaviors()
{
return [
'timestamp' => [
'class' => 'yii\behaviors\TimestampBehavior',
'attributes' => [
ActiveRecord::EVENT_BEFORE_INSERT => ['created_at', 'updated_at'],
ActiveRecord::EVENT_BEFORE_UPDATE => ['updated_at'],
],
'value' => new Expression('NOW()'),
],
];
}