how to remove a column from export config - yii2

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
],

Related

Yii2 gridview buttons problem (possibly after pjax)

<?= GridView::widget([
'id' => 'CompanyGrid',
'dataProvider' => $dataProvider,
'filterModel' => $searchModel,
'floatHeader'=>true,
'floatOverflowContainer'=>true,
'floatHeaderOptions'=>['top'=>'0'],
'pjax'=>true,
'pjaxSettings' => [
'options' => [
'enablePushState' => false,
'enableReplaceState' => true,
]
],
'hover'=>true,
'toolbar' => [
'{export}',
'{toggleData}'
],
'panel' => [
'heading'=>'<h3 class="panel-title"><i class="glyphicon glyphicon-globe"></i> Companies</h3>',
'type'=>'secondary',
'before'=>Html::button('Create Company', ['value'=>Url::to('index.php?r=Company/company/create'), 'title' => 'Create Company', 'class' => 'btn btn-success', 'id' => 'modalButton']),
'after'=>false,
],
'columns' => [
['class' => 'kartik\grid\SerialColumn'],
'CompanyID',
'CompanyName',
['class' => 'kartik\grid\ActionColumn',
'template' => '{view} {update} {delete}',
'buttons' => [
'view' => function($url, $model){
return Html::a('<span class="fa fa-eye"></span>', ['view', 'id' => $model->CompanyID], [
'class' => 'activity-view-link',
'data-pjax'=>'w0',
'title' => Yii::t('yii', 'View Company: '.$model->CompanyID),
'data-toggle' => 'modal',
'data-target' => '#modal',
]);
},
'update' => function($url, $model){
return Html::a('<span class="fa fa-edit"></span>', ['update', 'id' => $model->CompanyID], [
'class' => 'activity-view-link',
'title' => Yii::t('yii', 'Edit Company: '.$model->CompanyID),
'data-toggle' => 'modal',
'data-target' => '#modal',
]);
},
'delete' => function($url, $model){
return Html::a('<span class="fa fa-trash"></span>', ['delete', 'id' => $model->CompanyID], [
'class' => '',
'data' => [
'confirm' => 'Are you absolutely sure? This action is not reversible',
'method' => 'post',
],
]);
}
],
],
],
]); ?>
In Controller
public function actionView($id)
{
$model = Company::findOne($id);
return $this->renderAjax('view', [
'model' => $model,
]);
}
I am new in yii2-advance-apps and i am trying to solve this problem. Already worked on this problem and cannot find any solution for this.
The problem is when I click on the gridview actions buttons, it works. However, after PJax, the button just don't work anymore.
However, if i reload the page, the button works again.
How to solve this problem. Thank you in advance.
'data-pjax' => 0, in action buttons options and not 'w0'

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.

Codeception Object configuration must be an array

I am trying to run basic codeception test but what I get is the error bellow:
Backend\tests.functional Tests (1) -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
E LoginCest: Login user (0.01s)
------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
1) LoginCest: Login user
Test tests/functional/LoginCest.php:loginUser
[yii\base\InvalidConfigException] Object configuration must be an array containing a "class" element.
Scenario Steps:
1. $I->amOnPage("/admin/user/login") at tests/functional/LoginCest.php:18
#1 /home/projects/toma/toma-coreshop/vendor/yiisoft/yii2/BaseYii.php:353
#2 /home/projects/toma/toma-coreshop/vendor/yiisoft/yii2/base/Module.php:427
#3 /home/projects/toma/toma-coreshop/vendor/yiisoft/yii2/base/Module.php:586
#4 /home/projects/toma/toma-coreshop/vendor/yiisoft/yii2/base/Module.php:522
#5 /home/projects/toma/toma-coreshop/vendor/yiisoft/yii2/web/Application.php:103
#6 /home/projects/toma/toma-coreshop/vendor/symfony/browser-kit/Client.php:351
#7 Codeception\Lib\InnerBrowser->amOnPage
#8 /home/projects/toma/toma-coreshop/backend/tests/_support/_generated/FunctionalTesterActions.php:526
#9 /home/projects/toma/toma-coreshop/backend/tests/functional/LoginCest.php:18
#10 backend\tests\functional\LoginCest->loginUser
Time: 251 ms, Memory: 16.00MB
There was 1 error:
---------
ERRORS!
Tests: 1, Assertions: 0, Errors: 1.
The errors flows one by one on every step whit those tests. My configuration file looks like (backend\codeception.yml):
namespace: backend\tests
actor: Tester
paths:
tests: tests
log: tests/_output
data: tests/_data
helpers: tests/_support
settings:
bootstrap: _bootstrap.php
colors: true
memory_limit: 1024M
modules:
config:
Yii2:
configFile: 'config/test.php'
In my test.php I have:
<?php
$config = yii\helpers\ArrayHelper::merge(
require(__DIR__ . '/main.php'),
require(__DIR__ . '/main-local.php'),
[
'id' => 'app-backend-test',
'components' => [
'db' => [
'class' => 'yii\db\Connection',
'dsn' => 'mysql:host=localhost;dbname=coreshop',
'username' => '*****',
'password' => '*****',
'charset' => 'utf8',
//'enableSchemaCache' => true,
],
]
]
);
return $config;
And finally my LoginCest.php:
/**
* Class LoginCest
*/
class LoginCest
{
/**
* #param FunctionalTester $I
*/
public function loginUser(FunctionalTester $I)
{
$I->amOnPage('/admin/user/login');
$I->fillField('Username', '***');
$I->fillField('Password', '***');
$I->click('Вход');
}
}
I followed the instruction given on the codeception site for the Yii2-advanced template. I am trying to test on old project so it is not newly installed Yii2-advanced if that matters in this case. Thank you!
EDIT
Main.php:
$params = array_merge(
require(__DIR__ . '/../../common/config/params.php'),
require(__DIR__ . '/../../common/config/params-local.php'),
require(__DIR__ . '/params.php'),
require(__DIR__ . '/params-local.php')
);
return [
'id' => 'app-backend',
'name' => 'Online Shop Admin',
'homeUrl' => '/admin',
'basePath' => dirname(__DIR__),
'controllerNamespace' => 'backend\controllers',
'language' => 'bg-BG',
'bootstrap' => [
[
'class' => 'app\components\LanguageSelector',
'supportedLanguages' => [],
],
'log',
'devicedetect'
],
'modules' => [
'user' => [
'controllerMap' => [
'security' => 'backend\controllers\user\SecurityController',
'admin' => 'backend\controllers\user\AdminController',
],
'modelMap' => [
'User' => 'backend\models\User',
'SettingsForm' => 'backend\models\SettingsForm',
'Profile' => 'backend\models\Profile',
/*'UserSearch' => 'backend\models\UserSearch',*/
],
'rememberFor' => 1209600,
],
'statistics' => [
'class' => 'backend\modules\statistics\Module',
],
'catalogue' => [
'class' => 'backend\modules\catalogue\Module',
],
'news' => [
'class' => 'backend\modules\news\Module',
],
'sales' => [
'class' => 'backend\modules\sales\Module',
],
'wasteManagment' => [
'class' => 'backend\modules\wasteManagment\WasteManagment',
],
'help' => [
'class' => 'backend\modules\help\HelpInfo',
],
'marketing' => [
'class' => 'backend\modules\marketing\Module',
],
'translation' => [
'class' => 'backend\modules\translation\Module',
],
'gii' => [
'class' => 'yii\gii\Module',
'allowedIPs' => ['127.0.0.1', '::1', '192.168.33.1'], // adjust this to your needs
'generators' => [
'crud' => [
'class' => 'backend\templates\crud_v1\Generator',
'templates' => ['mycrud' => '#backend/templates/crud_v1/default']
],
'model' => [
'class' => 'backend\templates\model_v1\Generator',
'templates' => ['mymodel' => '#backend/templates/model_v1/default']
],
/*'crud' => [
'class' => 'backend\templates\crud_module_v1\Generator',
'templates' => ['mycrudmodule' => '#backend/templates/crud_module_v1/default']
],
'model' => [
'class' => 'backend\templates\model_module_v1\Generator',
'templates' => ['mymodelmodule' => '#backend/templates/model_module_v1/default']
],*/
],
],
],
'components' => [
'assetManager' => [
'bundles' => [
'yii\bootstrap\BootstrapAsset' => [
'css' => [],
],
'yii\bootstrap\BootstrapPluginAsset' => [
'js' => []
],
'yii\web\JqueryAsset' => [
'js' => []
],
'wbraganca\dynamicform\DynamicFormAsset' => [
'js' => [
'/admin/dist/js/yii2-dynamic-form.js'
]
],
],
],
'urlManagerBackend' => [
'class' => 'yii\web\urlManager',
'baseUrl' => (isset($_SERVER['HTTPS']) ? "https" : 'http') . "://toma-coreshop.webbuild.com/admin",
'enablePrettyUrl' => true,
'showScriptName' => false,
],
'request' => [
'baseUrl' => '/admin',
'cookieValidationKey' => 'sew4789vb7834tvnv78',
'csrfParam' => '_backendCSRF',
],
'user' => [
'identityClass' => 'backend\models\User',
'enableAutoLogin' => true,
'loginUrl' => [ 'user/login'],
'identityCookie' => [
'name' => '_backendUser', // unique for backend
]
],
/*'session' => [
'name' => '_backendSessionId',
'savePath' => __DIR__ . '/../runtime/sessions',
],*/
'view' => [
'theme' => [
'pathMap' => [
'#dektrium/user/views' => '#backend/views/user',
'#dektrium/rbac/views' => '#backend/views/rbac',
],
],
],
'log' => [
'traceLevel' => YII_DEBUG ? 3 : 0,
'targets' => [
[
'class' => 'yii\log\FileTarget',
'levels' => ['error', 'warning'],
],
],
],
'mailer' => [
'class' => 'yii\swiftmailer\Mailer',
],
'translate' => [
'class' => 'backend\components\Translate'
],
'tabSettings' => [
'class' => 'backend\components\TabSettings'
],
'system' => [
'class' => 'backend\components\System'
],
'moneyConvertor' => [
'class' => 'backend\components\MoneyConvertor'
],
'moneyWords' => [
'class' => 'backend\components\MoneyWords'
],
'OutData' => [
'class' => 'backend\components\OutData'
],
'MakeURL' => [
'class' => 'backend\components\MakeURL'
],
'makeUrl' => [
'class' => 'frontend\components\MakeURL'
],
'image' => [
'class' => 'backend\components\Image'
],
'formatter' => [
'class' => 'yii\i18n\Formatter',
'nullDisplay' => '',
],
'devicedetect' => [
'class' => 'alexandernst\devicedetect\DeviceDetect'
],
'errorHandler' => [
'errorAction' => 'site/error',
],
'urlManager' => [
'enablePrettyUrl' => true,
'showScriptName' => false,
'enableStrictParsing' => false,
'rules' => [
'profile' => 'user/settings/profile',
],
],
'i18n' => [
'translations' => [
'app*' => [
'class' => 'yii\i18n\PhpMessageSource',
'basePath' => '#backend/messages',
'sourceLanguage' => 'bg',
'fileMap' => [
'app' => 'app.php',
],
],
'help*' => [
'class' => 'yii\i18n\PhpMessageSource',
'basePath' => '#backend/modules/help/messages',
'sourceLanguage' => 'bg',
'fileMap' => [
'help' => 'help.php',
],
],
'sales*' => [
'class' => 'yii\i18n\PhpMessageSource',
'basePath' => '#backend/modules/sales/messages',
'sourceLanguage' => 'bg',
'fileMap' => [
'catalogue' => 'sales.php',
],
],
'statistics*' => [
'class' => 'yii\i18n\PhpMessageSource',
'basePath' => '#backend/modules/statistics/messages',
'sourceLanguage' => 'bg',
'fileMap' => [
'catalogue' => 'statistics.php',
],
],
'catalogue*' => [
'class' => 'yii\i18n\PhpMessageSource',
'basePath' => '#backend/modules/catalogue/messages',
'sourceLanguage' => 'bg',
'fileMap' => [
'catalogue' => 'catalogue.php',
],
],
'marketing*' => [
'class' => 'yii\i18n\PhpMessageSource',
'basePath' => '#backend/modules/marketing/messages',
'sourceLanguage' => 'bg',
'fileMap' => [
'catalogue' => 'news.php',
],
],
'news*' => [
'class' => 'yii\i18n\PhpMessageSource',
'basePath' => '#backend/modules/news/messages',
'sourceLanguage' => 'bg',
'fileMap' => [
'catalogue' => 'news.php',
],
],
'message*' => [
'class' => 'yii\i18n\PhpMessageSource',
'basePath' => '#backend/modules/translation/messages',
'sourceLanguage' => 'bg',
'fileMap' => [
'message' => 'message.php',
],
],
'kvgrid*' => [
'class' => 'yii\i18n\PhpMessageSource',
'basePath' => '#backend/messages/kvgrid',
'sourceLanguage' => 'bg',
'fileMap' => [
'kvgrid' => 'kvgrid.php',
],
],
],
],
],
'params' => $params,
];
Main-local.php:
$config = [
'components' => [
'request' => [
// !!! insert a secret key in the following (if it is empty) - this is required by cookie validation
'cookieValidationKey' => 'ud_6581BcmdaOC-RoK4LznBhsD7W4pyU',
],
],
'container' => [
'definitions' => [
kartik\grid\GridView::class => [
'krajeeDialogSettings' => ['overrideYiiConfirm' => false],
'responsiveWrap' => false,
'bordered' => false,
'tableOptions' => [
'class' => 'table full-color-table full-dark-table hover-table',
],
'resizableColumns' => true,
'hover' => true,
'layout' => "{items}\n{summary}\n{pager}",
'rowOptions' => function ($model) {
if(!empty($model->id))
return ['data-id' => $model->id];
else
return;
},
],
],
],
];
if (YII_ENV_DEV) {
// configuration adjustments for 'dev' environment
$config['bootstrap'][] = 'debug';
$config['modules']['debug'] = [
'class' => 'yii\debug\Module',
];
$config['modules']['debug']['allowedIPs'] = ['*'];
$config['bootstrap'][] = 'gii';
$config['modules']['gii'] = [
'class' => 'yii\gii\Module',
];
$config['modules']['gii']['allowedIPs'] = ['*'];
}
return $config;

Yii 2 Export (Kartik) Menu - How can I make Dropdownlist (Exportcolumns) scrollable?

I'm using Yii2 basic and the extension kartik\export\ExportMenu.
How can I make Dropdownlist (Exportcolumns) scrollable? I have so many columns to choose, so it doesn't show me all of them when I'm working with a screen resolution of 100%. Some of them are cut off.
Dropdown columns:
<?php
$gridColumns = [
['class' => 'yii\grid\SerialColumn'],
['attribute'=>'Personen ID','value' => 'PID'],
['attribute'=>'Titel','value' => 'PTitel'],
['attribute'=>'Anrede','value' => 'PAnrede'],
['attribute'=>'Vorname','value' => 'PVorname'],
['attribute'=>'Nachname','value' => 'PNachname'],
['attribute'=>'Private Telefonnummer','value' => 'PTelefon'],
['attribute'=>'Private Mobiltelefonnummer','value' => 'PMobil'],
['attribute'=>'Privatmail','value' => 'PEmail'],
['attribute'=>'Private Webadresse','value' => 'PWebadresse'],
['attribute'=>'Firmen ID','value' => 'FID'],
['attribute'=>'Firmenname','value' => 'FName'],
['attribute'=>'Firmenbezeichnung','value' => 'FNamenszusatz'],
['attribute'=>'Ist Zentrale','value' => 'FIstZentrale'],
['attribute'=>'Beziehungs ID','value' => 'RID'],
['attribute'=>'Kommentar','value' => 'RKommentar'],
['attribute'=>'Funktion','value' => 'FUName'],
['attribute'=>'Zweitfunktion','value' => 'FUName'],
['attribute'=>'Branche','value' => 'BRName'],
['attribute'=>'Kategorie','value' => 'KName'],
['attribute'=>'Erstellt am','value' => 'RErstelltAm'],
['attribute'=>'Erstellt von','value' => 'RErstelltVon'],
['attribute'=>'Bearbeitet am','value' => 'RLetzteBearbeitung'],
['attribute'=>'Bearbeitet von','value' => 'RLetzterBearbeiter'],
['attribute'=>'Adress ID','value' => 'AID'],
['attribute'=>'Straße','value' => 'AStrasse'],
['attribute'=>'Hausnummer','value' => 'AHausnummer'],
['attribute'=>'Adresszusatz','value' => 'AAdresszusatz'],
['attribute'=>'PLZ','value' => 'APostleitzahl'],
['attribute'=>'Ort','value' => 'AOrt'],
['attribute'=>'Land','value' => 'ALand'],
['attribute'=>'Bundesland','value' => 'ABundesland'],
[ 'attribute'=>'Firmentelefon','value' => 'AFirmentelefon'],
[ 'attribute'=>'Firmen Email','value' => 'AFirmenEmail'],
[ 'attribute'=>'Webadresse','value' => 'AWebadresse'],
[ 'attribute'=>'Adresskennung','value' => 'AKennung'],
];
Export widget in view:
The class attributes in columnSelectorOptions and columnSelectorMenuOptions don't make any difference.
echo ExportMenu::widget([
'columnBatchToggleSettings'=>['label'=>'Alle Wählen'],
'dropdownOptions' =>
[
'label' => 'Exportieren',
'class' => 'btn btn-wkm'
],
'columnSelectorOptions'=>
[
'label' => 'Exportspalten',
'class' => 'btn btn-default dropdown-toggle',
'scrollable'=> true,
],
'columnSelectorMenuOptions' =>
[
'class' => 'dropdown-menu scrollable-menu',
'role'=> 'menu'
],
'dataProvider' => $dataProviderClone,
'columns' => $gridColumns,
'exportConfig' =>
[
ExportMenu::FORMAT_TEXT => false,
ExportMenu::FORMAT_HTML => false,
ExportMenu::FORMAT_EXCEL => false,
ExportMenu::FORMAT_PDF => false,
ExportMenu::FORMAT_EXCEL_X =>
[
'label' => 'EXCEL',
]
],
'container'=>['class'=>'btn-group pull-left', 'style'=> 'margin: 5px']
]);
?>
I found a solution :) You just have to add a style attribute to the columnSelectorMenuOptions. Changing the site.css had no impact.
'columnSelectorMenuOptions' =>
[
'style'=> 'overflow-y: scroll, height: auto;
max-height: 200px; overflow-x: hidden;',
]

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

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}; }'),
],
],
]),
],