Yii2: Select2, How to set initValueText in Gridview or Tabularform? - yii2

I need to set initValueText for Select2, which is in loop, like gridview or Tabularform. but I don't know how to set right value for each.
<?= TabularForm::widget([
'dataProvider' => $dataProvider,
'form' => $form,
'actionColumn' => false,
'checkboxColumn' => false,
'attributeDefaults' => [
'type' => TabularForm::INPUT_RAW,
],
'attributes' => [
'test' => [
'type' => Form::INPUT_WIDGET,
'widgetClass' => Select2::className(),
'options' => [
'name' => 'test',
'options' => [
'class' => 'test-to-select',
],
'pluginOptions' => [
'allowClear' => true,
'minimumResultsForSearch' => 'Infinity',
'ajax' => [
'url' => Url::to(['/test/get-list']),
'dataType' => 'json',
'data' => new JsExpression('function(term,page) {
return {term : term.term};
}'),
'results' => new JsExpression('function(data,page) {
return {results:data.results};
}'),
'cache' => true
]
],
'initValueText' => 'Selected Text' /// how can I set this in gridview or Tabularform?
],
],
]
]) ?>
Of course this is not working,
'initValueText' => function($model){
retur $model->textValue;
}
Any help would be appreciated.

Into tabularform if you want dynamic initValueText, you can use options closure in this manner:
'test' => [
'type' => Form::INPUT_WIDGET,
'widgetClass' => Select2::className(),
'options' => function($model, $key, $index, $widget) {
$initValueText = empty($model['textValue']) ? '' : $model['textValue'];
return [
'name' => 'test',
'options' => [
'class' => 'test-to-select',
],
'initValueText' => $initValueText,
'pluginOptions' => [
'allowClear' => true,
'minimumResultsForSearch' => 'Infinity',
'ajax' => [
'url' => Url::to(['/test/get-list']),
'dataType' => 'json',
'data' => new JsExpression('function(term,page) {
return {term : term.term};
}'),
'results' => new JsExpression('function(data,page) {
return {results:data.results};
}'),
'cache' => true
]
],
];
}
],

If for example attribute for city, so try this..
$cityDesc = empty($model->city) ? '' : City::findOne($model->city)->description;
'initValueText' => $cityDesc, // set the initial display text
For init value first assign value to $model attribute, if you should not assign so this attribute can take value.

Set the data parameter with the array including the option you want to show. For example for cities:
'options' => [
'data' => \yii\helpers\ArrayHelper::map(\app\models\City::find()->orderBy('id')->asArray()->all(), 'id', 'name'),
]

try to put inside the options instead ouside
'widgetClass' => Select2::className(),
'options' => [
'initValueText' => 'Selected Text'

Don't use isset it return error if more the one filter are use there.
[
'attribute' => 'ad_partner_id',
'value' => function ($model, $key, $index, $widget) {
return $model->partner->name;
},
'filter' => Select2::widget([
'model' => $searchModel,
'initValueText' => !empty($searchModel->ad_partner_id) ? $searchModel->partner->name : "",
'attribute' => 'ad_partner_id',
'options' => ['placeholder' => Yii::t('app', 'Search Partner ...')],
'pluginOptions' => ['allowClear' => true, 'autocomplete' => true,
'ajax' => ['url' => Url::base() . '/partner/get-partners',
'dataType' => 'json',
'data' => new JsExpression('function(params) { return {q:params.term}; }'),
],
],
]),
],

Related

Update data in Kartik Detailview is not working

I've detail showed using Kartik Detail View. This widget has Edit inline function by clicking pencil icon button in top right side like this.
But then the table doesn't be editable :
And nothing happen, my data still the same, my update not success. It's possible to solve my problem? Thanks.
I have read the official guide and it looks identical:
https://demos.krajee.com/detail-view
This is my view code:
<?php echo DetailView::widget([
'model' => $modelAnagrafiche,
'responsive' => true,
'mode' => 'edit',
'enableEditMode' => true,
'buttons1' => '{update}',
'panel' => [
'type' => 'primary',
'heading' => 'Contratto' . ' : ' . $modelAnagrafiche >cognome_ragione_sociale . ' ' . $modelAnagrafiche->nome
],
'attributes' => [
[
'group'=>true,
'label'=>'Sezione Anagrafica',
'rowOptions'=>['class'=>'table-primary']
],
[
'columns' => [
[
'attribute' => 'cognome_ragione_sociale',
'displayOnly' => true,
'valueColOptions' => ['style' => 'width:30%']
],
[
'attribute' => 'nome',
'format' => 'raw',
'valueColOptions' => ['style' => 'width:30%'],
'displayOnly' => true,
'type' => DetailView::INPUT_TEXT,
],
],
],
[
'columns' => [
[
'attribute' => 'codice_fiscale',
'displayOnly' => true,
'valueColOptions' => ['style' => 'width:30%']
],
[
'attribute' => 'partita_iva',
'format' => 'raw',
'valueColOptions' => ['style' => 'width:30%'],
'displayOnly' => true
],
],
],
[
'columns' => [
[
'attribute' => 'tipo_documento',
'displayOnly' => true,
'valueColOptions' => ['style' => 'width:30%'],
'format' => 'raw',
'value' => $modelAnagrafiche->tipoDocumento,
],
[
'attribute' => 'numero_documento',
'format' => 'raw',
'valueColOptions' => ['style' => 'width:30%'],
'displayOnly' => true
],
],
],
[
'columns' => [
[
'attribute' => 'data_nascita',
'displayOnly' => true,
'format' => 'date',
'type' => DetailView::INPUT_DATE,
'widgetOptions' => [
'pluginOptions' => ['format' => 'yyyy-mm-dd']
],
],
[
'attribute' => 'id_provincia_nascita',
'displayOnly' => true,
'valueColOptions' => ['style' => 'width:30%'],
'format' => 'raw',
'value' => $modelAnagrafiche->provinciaNascitaNome,
'label' => 'Provincia Nascita'
],
],
],
[
'columns' => [
[
'attribute' => 'id_comune_nascita',
'displayOnly' => true,
'format' => 'raw',
'value' => $modelAnagrafiche->comuneNascitaNome,
'label' => 'Comune Nascita'
],
],
],
],
]);
?>
This is the action in my controller:
public function actionUpdateAnagrafica()
{
$post = Yii::$app->request->post();
if (empty($post['Anagrafiche']['id'])) {
throw new NotFoundHttpException('Non esiste nessuna anagrafica.');
}
$modelAnagrafiche = Anagrafiche::findOne($post['Anagrafiche']['id']);
if ($modelAnagrafiche->load($post) && $modelAnagrafiche->save()) {
return $this->redirect(['view', 'id' => $modelAnagrafiche->id]);
} else {
return $this->render('update-anagrafica', [
'modelAnagrafiche' => $modelAnagrafiche,
]);
}
}
You have to remove all the displayOnly attributes.
According to the official guide:
displayOnly: boolean|Closure, if the input is to be set to as display
only in edit mode. If set to true, no editable form input will be
displayed, instead this will display the formatted attribute value.

how to remove a column from export config

i am creating an export to excel configuration but i want to export some particular columns any idea??
'exportConfig' => [
GridView::EXCEL => [
'showHeader'=>$title,
'showFooter' => true,
'showCaption' => true,
'filename'=>$title.date("Ymd",strtotime($searchModel->start_date)),
'mime' => 'application/vnd.ms-excel',
'config' => [
'worksheet' => 'ExportWorksheet',
'cssFile' => ''
]
],
],
'export'=>[
'label'=>"Download",
'icon' =>'export',
'showConfirmAlert'=>false,
'target'=>GridView::TARGET_SELF,
'header'=>false
],
if you are using KartikGridView you could set the column you want to export in the GridView Widget
'columns' => [
['class' => 'yii\grid\SerialColumn'],
'your_col1',
'your_col2',
'your_col3',
....
];
<?= GridView::widget([
'dataProvider' => $dataProvider,
'filterModel' => $searchModel,
'columns' => $gridColumns,
'showPageSummary' => true,
'exportConfig' => [
GridView::EXCEL => [
'showHeader'=>$title,
'showFooter' => true,
'showCaption' => true,
'filename'=>$title.date("Ymd",strtotime($searchModel->start_date)),
'mime' => 'application/vnd.ms-excel',
'config' => [
'worksheet' => 'ExportWorksheet',
'cssFile' => ''
]
],
],
'export'=>[
'label'=>"Download",
'icon' =>'export',
'showConfirmAlert'=>false,
'target'=>GridView::TARGET_SELF,
'header'=>false
],

Add Custom Button in Kartik Yii2 Kartik DetailView

I already search and try every forum and example.
I am using the Kartik\DetailViwew in Yii2 and I can´t manage to put a single custom button in the buttons1 option.
The code I am working on:
echo DetailView::widget([
'model' => $model,
'attributes' => $attributes,
'mode'=>Yii::$app->request->get('edit')=='t' ? DetailView::MODE_EDIT : DetailView::MODE_VIEW,
'panel'=>[
'heading'=>$this->title,
'type'=>DetailView::TYPE_INFO,
],
'buttons1' => '{update}',
'bordered' => 'true',
'striped' => $striped,
'condensed' => $condensed,
'responsive' => $responsive,
'hover' => $hover,
'hAlign'=>$hAlign,
'vAlign'=>$vAlign,
'fadeDelay'=>$fadeDelay,
'deleteOptions'=>[ // your ajax delete parameters
'params' => ['id' => $model->p_id, 'custom_param' => true],
'url'=>['delete', 'id' => $model->p_id],
]
]);
In the
'buttons1' => '{update}',
According to the example http://demos.krajee.com/detail-view, there is a way to customize.
But there is no example. And the documentation not explain how to do this.
Can anyone help?
After research and some tryings, I did it by this way, you have to enable the edit mode (to show buttons), and modify the defatul template ({buttons}{title}), as this template is replaced if the template exists in vender grideview constants, just inject your code to add any button u want. Is not the rigth solution, but is a workaround that works well
<?php
$button1 = Html::a('<i class="glyphicon glyphicon-trash"></i>', Url::to(['delete', 'id' => $model->id]), [
'title' => 'Eliminar',
'class' => 'pull-right detail-button',
'data' => [
'confirm' => '¿Realmente deseas eliminar este elemento?',
'method' => 'post',
]
]);
$button2 = Html::a('<i class="glyphicon glyphicon-pencil"></i>', Url::to(['actualizar', 'id' => $model->id]), [
'title' => 'Actualizar',
'class' => 'pull-right detail-button',
]);
?>
<?=
DetailView::widget([
'model' => $model,
'hover' => true,
'hideAlerts' => true,
'enableEditMode' => true,
'mode' => DetailView::MODE_VIEW,
'hAlign' => 'left',
'panel' => [
'heading' => '&nbsp',
'type' => DetailView::TYPE_DEFAULT,
'headingOptions' => [
'template' => "$button1 $button2 {title}"
]
],
'attributes' => [
'id',
'identificacion',
'nombre',
],
])
?>
Try it like this:
'buttons1' => Html::a('<i class="glyphicon glyphicon-trash"></i>', Url::to(['delete', 'id' => $model->id]), [
'title' => 'Eliminar',
'class' => 'pull-right detail-button',
'data' => [
'confirm' => '¿Realmente deseas eliminar este elemento?',
'method' => 'post',
]
]),
If you have more than one button, try it like this:
$button1 = Html::a('<i class="glyphicon glyphicon-trash"></i>', Url::to(['delete', 'id' => $model->id]), [
'title' => 'Eliminar',
'class' => 'pull-right detail-button',
'data' => [
'confirm' => '¿Realmente deseas eliminar este elemento?',
'method' => 'post',
]
]);
$button2 = Html::a('<i class="glyphicon glyphicon-pencil"></i>', Url::to(['actualizar', 'id' => $model->id]), [
'title' => 'Actualizar',
'class' => 'pull-right detail-button',
]);
'buttons1' => "{$button1} {$button2}",

Setting empty text in kartik dynagrid

Am using kartik dynagrid and i would like to setup a text that shows when the dataprovider returns empty
The grid
echo DynaGrid::widget([
'columns' => $columns,
'showPersonalize' => true,
'emptyText'=>'Sorry all pr have pritems',///-----------------This is what i had set
'options' => ['id' => 'assignsolic-grid'],
'gridOptions' => [
'options' => ['id' => 'grid'],
'dataProvider' => $dataProvider,
'filterModel' => $searchModel,
'showPageSummary'=>false,
'pager' => [
'firstPageLabel' => 'First',
'lastPageLabel' => 'Last',
'maxButtonCount' => 10,
],
'panel' => [
'type' => GridView::TYPE_PRIMARY,
// 'heading' => '<h3 class="panel-title"><i class="glyphicon glyphicon-book"></i> </h3>',
'before'=>'<i>Select the Prs to assign solicitation and then click the Assign Solicitation button</i>',
'after' =>
Html::button(' <i class=" glyphicon glyphicon-road "></i> Assign Solicitation ', ['value' => Url::to('assignsolc'),'class' => 'btn btn-danger', 'id' => 'assignsolic']),
'footer' => false
],
'toolbar' => [
['content' => '{dynagridFilter}{dynagridSort}{dynagrid}'],
'{export}',
'{toggleData}'
],
'pjax' => true,
'bordered' => false,
'striped' => true,
'condensed' => true,
'responsive' => true,
'responsiveWrap' => false,
'containerOptions'=>['style'=>'overflow:scroll'],
]
]) ;
This returs an error of Setting unknown property: kartik\dynagrid\DynaGrid::emptyText how can i set the empty text
You can define the value for null display directly in confi/main.php formatter component
'components' => [
.......
'formatter' => [
'class' => 'yii\i18n\Formatter',
'dateFormat' => 'dd.MM.yyyy',
'decimalSeparator' => ',',
'thousandSeparator' => ' ',
'currencyCode' => 'EUR',
'nullDisplay' => '', // **** this param
],
.....
Otherwise if the widget don't provide a proper attribute you can use an anonymous function for value
[
'attribute' => 'your_attribute',
'value' => function ($model) {
if ( $model->your_attribute == NULL) {
return 'Sorry all pr have pritems';
} else {
return $model->your_attribute;
}
},
],
Since am using $dataProvider i found out that i just have to check if the dataProvider is empty by
if (!$dataProvider->totalCount > 0) { pass in message to display }
else{?>
SHOW THE GRID HERE
<?php
}
?>
?>

Yii2 kartik typeahead - get number of suggestions

I'm using kartik's typeahead widget for Yii2 in a view:
echo \kartik\typeahead\Typeahead::widget([
'name' => 'serial_product',
'options' => [
'placeholder' => 'Filter as you type ...',
'autofocus' => "autofocus"
],
'scrollable' => TRUE,
'pluginOptions' => [
'highlight' => TRUE,
'minLength' => 3
],
'dataset' => [
[
'remote' => Url::to(['transfers/ajaxgetinventoryitemsnew']) . '?search=%QUERY',
'limit' => 10
]
],
'pluginEvents' => [
"typeahead:selected" => "function(obj, item) { add_item(item.id); return false;}",
],
]);
How can i get the number of loaded suggestions after the remote dataset is retrieved to execute a javascript function like:
displaynumber(NUMBEROFSUGGESTIONS);
After checking through the source of kartiks widget i came up with the following solution:
echo \kartik\typeahead\Typeahead::widget([
'name' => 'serial_product',
'options' => [
'placeholder' => 'Filter as you type ...',
'autofocus' => "autofocus",
'id' => 'serial_product'
],
'scrollable' => TRUE,
'pluginOptions' => [
'highlight' => TRUE,
'minLength' => 3
],
'dataset' => [
[
'remote' => [
'url' => Url::to(['transfers/ajaxgetinventoryitemsnew']) . '?search=%QUERY',
'ajax' => ['complete' => new JsExpression("function(response)
{
jQuery('#serial_product').removeClass('loading');
checkresult(response.responseText);
}")]
],
'limit' => 10
]
],
'pluginEvents' => [
"typeahead:selected" => "function(obj, item) { checkresult2(item); return false;}",
],
]);
where response.responseText is containing the response from server (json).
function checkresult(response) {
var arr = $.parseJSON(response);
console.log(arr.length);
}
With this function i can get then count of suggestions delivered from server.