Yii2, Set multiple Value Select2 - php

I have load select2 data like this :
$data = ArrayHelper::map(ContactGroups::find()->where(['group_status'=>'ACTIVE'])->asArray()->all(),'group_id', 'group_name');
echo $form->field($model, 'group_id')->widget(Select2::classname(), [
'data' => $data,
'model' => $model,
'language' => 'en',
'options' => ['placeholder' => Yii::t('modules','Pilih Kelompok')],
'pluginOptions' => [
'allowClear' => true,
'multiple' => true,
],
])->label('Kelompok');
$data variable returning result :
Array
(
[1] => Tanpa Kategori
[3] => Bisnis
[4] => Kawan
[5] => Bisnis Kerang
[6] => Bisnis Selang
[99] => Keluarga
)
and select2 working properly, but I can't show selected value or initial value. is I've missed something ?

you add tags property in pluginOptions for multiple selection like....
$data = ArrayHelper::map(ContactGroups::find()->where(['group_status'=>'ACTIVE'])->asArray()->all(),'group_id', 'group_name');
foreach($data as $d)
$row[]=$d;
echo $form->field($model, 'group_id')->widget(Select2::classname(), [
'language' => 'en',
'name' => 'group_id[]',
'options' => ['placeholder' => ''],
'pluginOptions' => [
'tags' => $row,
'allowClear' => true,
'multiple' => true
],
])->label('Kelompok');
You show Demo

Try using like this.. At the time of updating we need to take already selected values in 1 variable and all values in 1 variable.. and send this to select2.
$query = NewsTags::find()->where(['news_id' => $model->id])->all();
$services = array();
$services_id_list = array();
foreach ($query as $ds) {
$tag_id = $ds->tag_id;
$tag_name = Tags::findOne($tag_id)->tag_name;
$services[$ds->tag_id] = $tag_name;
array_push($services_id_list, $ds->tag_id);
}
$data= ArrayHelper::map(Tags::find()->where([])->all(),'id','tag_name');
echo Select2::widget([
'name' => 'NewsTags[tag_id][]',
'id' => 'newstags-tag_id',
'value' => $services_id_list,
'data' => $data,
'maintainOrder' => true,
'options' => [
'placeholder' => 'Select a Service ...',
'multiple' => true
],
'pluginOptions' => [
'tags' => true,
'maximumInputLength' => 10
],
]);
here NewsTags[tag_id][] is the model and its column. we are not directly calling $model->attribute here

Having a look at the code of kartik\base\InputWidget line 190 :
if ($this->hasModel()) {
$this->name = !isset($this->options['name']) ? Html::getInputName($this->model, $this->attribute) : $this->options['name'];
$this->value = !isset($this->options['value'])? Html::getAttributeValue($this->model, $this->attribute) : $this->options['value'];
}
I've found out that, when loading data with AJAX, initial multiple values should be set in options[value] like this:
<?= $form->field($model, $attribute)->widget(Select2::className(), [
'initValueText' => $initText, // array of text to show in the tag for the selected items
'options' => [
'placeholder' => 'Any text you want ...',
'multiple' => true,
'class' => 'form-control',
'value' => $initIds, // array of Id of the selected items
],
whereas setting value next to initValueText leads to an array_combine error

Related

yii2 dep drop kartick dependencies

hi all i'm a noob of yii and i'm trying to get the kartiks to work, but I can't get them to load the dependency.I'm trying to make the kartik work but I can't get it to load the dependency, if I see the calls that are made through yii's built-in debugging the scream that is present in the 'URL' parameter is not really computed, I've also tried to write it fixed but it's not really thought.
If I do a simple echo, however, it comes back correct.
<?=$form->field($model, 'name')->
widget(Select2::classname(), ['data' => $listdataA,
'id' => 'invoice-name',
'options' => ['placeholder' => 'Seleziona anagrafica ...', 'id' => 'lvl-0',],
'pluginOptions' => [
'allowClear' => true
],
'pluginEvents' => [
'select2:select' => new JsExpression("function (e) {
var id=e.params.data.id;
$.get('index.php?r=invoice/get-location-address', {id: id}, function(data) {
if (data !== null) {
document.getElementById('piva').value=data.PIVA;
document.getElementById('indi').value=data.Indirizzo;
} else {
//if data wasn't found the alert.
alert('We\'re sorry but we couldn\'t load the the location data!');
}
});
}")]
]);
?>
<?= $form->field($model, 'attn')->textInput(['maxlength' => true, 'placeholder' => 'ATTN', 'id' => 'piva'])->label(false) ?>
<?= $form->field($model, 'address')->textarea(['rows' => 6, 'placeholder' => 'Address', 'id' => 'indi'])->label(false) ?>
<?php
echo $form->field($model, 'cd_contact')->widget(DepDrop::classname(), [
'options' => ['placeholder' => 'Select ...'],
'type' => DepDrop::TYPE_SELECT2,
'select2Options' => ['pluginOptions' => ['allowClear' => true]],
'pluginOptions' => [
'depends' => [Html::getInputId($model, 'name')], //['lvl-0'],
'url' => Url::to(['/contact/list']),
'loadingText' => 'caricamento dati ...',
]
]);
?>
in the controller
public function actionList() {
Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
$out = [];
if (isset($_POST['depdrop_parents'])) {
$id = end($_POST['depdrop_parents']);
$list = Contact::find()->andWhere(['id_ana_ref' => $id])->asArray()->all();
var_dump($list);
$selected = null;
if ($id != null && count($list) > 0) {
$selected = '';
foreach ($list as $i => $account) {
$out[] = ['id' => $account['id_contact'], 'name' => $account['Name']];
if ($i == 0) {
$selected = $account['id_contact'];
}
}
// Shows how you can preselect a value
return ['output' => $out, 'selected' => $selected];
}
}
solved if you put any java on kartick they avoid standard code
solution
<?=
$form->field($model, 'name')->
widget(Select2::classname(), ['data' => $listdataA,
'id' => 'invoice-name',
'options' => ['placeholder' => 'Seleziona anagrafica ...' ,'id' => 'lvl-0',],
'pluginOptions' => [
'allowClear' => true
],
]);
?>
<?= $form->field($model, 'attn')->textInput(['maxlength' => true, 'placeholder' => 'ATTN','onclick'=>'magsearch()', 'id' => 'piva'])->label(false) ?>
<?= $form->field($model, 'address')->textarea(['rows' => 6, 'placeholder' => 'Address', 'id' => 'indi'])->label(false) ?>
<?php
// $url = \yii\helpers\Url::to(['index.php?r=contact/list']);
echo $form->field($model, 'cd_contact')->widget(DepDrop::classname(), [
'data' => $datac,
'options' => ['placeholder' => 'carico ...'],
'type' => DepDrop::TYPE_SELECT2,
'select2Options' => ['pluginOptions' => ['allowClear' => true]],
'pluginOptions' => [
'depends' => ['lvl-0'],
'url' => Url::to(['/contact/list']),
// 'params' => ['lvl-0'],
'loadingText' => 'caricamento dati ...',
]
]);
?>

Show summary row and add it to the end of excel export

I'm trying to create summary row for my GridView which sums my quantity for current page and for all records seperately.
<?= GridView::widget([
'dataProvider' => $dataProvider,
'layout' => "{summary}\n{items}\n<div align='right'>{pager}</div>",
//'filterModel' => $searchModel,
'showPageSummary' => true,
'pageSummaryFunc' => GridView::F_SUM,
'columns' => [
['class' => 'yii\grid\SerialColumn'],
[
'class' => DataColumn::className(),
'attribute' => 'updated_at',
'format' => 'raw',
'value' => function ($model, $key, $index, $column){
return date('Y-m-d', $model->updated_at);
},
],
[
'label' => 'Ilość',
'attribute'=>'quantity',
'pageSummary' => true,
'value'=> function ($model, $key, $index, $column) {
return ($model->quantity) ? $model->quantity : '';
},
],
],
]); ?>
At the end i want to export sum for all records to my excel sheet at the bottom of my gridColumns. My export widget looks like:
$dataProviderAll->setSort([
'defaultOrder' => ['updated_at' => SORT_ASC]
]);
echo ExportMenu::widget([
'container' => ['class' => 'btn-group pull-right', 'role' => 'group'],
'dataProvider' => $dataProviderAll,
'columns' => $gridColumns,
'filename' => date('Y-m-d') . '_raport',
'target' => ExportMenu::TARGET_SELF,
'showConfirmAlert' => false,
'showColumnSelector' => false,
'fontAwesome' => true,
'dropdownOptions' => [
'label' => 'Eksportuj dane',
'class' => 'btn btn-primary btn-md'
],
'exportConfig' => [
ExportMenu::FORMAT_HTML => null,
ExportMenu::FORMAT_TEXT => null,
ExportMenu::FORMAT_EXCEL => null,
ExportMenu::FORMAT_PDF => null
]
]);
?>
All columns of model are already exported, but i need to add summary row for some of them into created excel file.
Im getting now error like this: Setting unknown property: kartik\grid\GridView::pageSummaryFunc
Does someone know how can I get this result?
I have fixed part where I wanted to get sum per page by replacing class column from yii to kartik. –

Select2 initial value doesn't appear

I Want to select value base on $_GET if exists soon.
Here is my code in view
<?php
/*if ($model->isNewRecord && !isset($model->agent_id_upper)) {
$model->agent_id_upper = 65;
} not working too*/
//$model->agent_id_upper = 65; ->not working
echo Select2::widget([
'model' => $model,
'name' => 'TbAgent[agent_id_upper]',
//'id' => 'to_id',
'initValueText' => '', // this only for ajax
'data' => $data,
'options' => [
'placeholder' => 'Choose Agent ...',
'multiple' => false,
//'selected' => 65, -> not working
//'value' => 65, -> not working
'class' => ''
],
]
);
?>
65 is ID of record, If selected then it should show username of thus ID.
But my problem is username of 65 is not selected, it only show place holder.
How I can fix this? and Please give me references.
already read this
yii2 select2 by kartik-v set default value
Yii2: Kartik Select2: Initial Value from Model Attribute
http://www.yiiframework.com/forum/index.php/topic/52278-kartik-select2-not-select-corretly/
but no luck with above.
Thanks in advance.
have you tried this? value is not inside options
<?= Select2::widget([
'model' => $model,
'name' => 'id',
'data' => $data,
'value' => 65,
'options' => [
'placeholder' => 'Choose Agent ...',
'multiple' => false,
]
]) ?>

How to add additional info into php array

I use this php code:
public function checkout(&$order, &$response)
{
$settings = Settings::get($order->seller_id);
$readon= 'maksājums';
$readon= $order->id;
$order->custom([
'payment_details' => [
'bank_name' => [ 'label' => $this->_->_('Bank Name'), 'value' => $settings->bank_name ],
'account_owner' => [ 'label' => $this->_->_('Account Owner'), 'value' => $settings->account_owner ],
//'bic' => [ 'label' => $this->_->_('BIC/SWIFT'), 'value' => $settings->bic ],
'iban' => ['label' => $this->_->_('IBAN'), 'value' => $settings->iban ],
'reason' => [ 'label' => $this->_->_('Reason for Payment'), 'value' => $readon],
],
]);
$response = [];
$response['redirect'] = $this->meta('manual_url');
return Payment::STATUS_OK;
}
Problem is that I want to add additional text on value readon. Right now $readon show only order number, but I want that it display text like "Please make payment for Order No.$order->id"
Just concatenate the string with what you need. Like this,
$readon= "Please make payment for Order No. ".$order->id;

Autocomplete in yii2

In Yii2 I want one of my input field to be autocomplete when user starts to type.Below is my code which uses Jui Autocomplete.
<?php
$items= ArrayHelper::map(Company::find()->all(), 'c_id', 'name');
echo AutoComplete::widget([
'model' => $model,
'attribute' => 'company',
'clientOptions' => [
'source' => $items,
],
]);?>
This is not working.When i printed my array, i got like
Array ( [1] => abc [2] => xyz [4] => pqr )
I got it working when i manually set like
$items=['abc','xyz','pqr'];
The reason may be my c_id's are not ordered?But i want to get the c_id value to be submitted!Any idea how to fix this?
This can be solved with the help of a hidden field input.Hope this will help somebody!
<?php
use yii\web\JsExpression;
$data = Company::find()
->select(['name as value', 'name as label','c_id as id'])
->asArray()
->all();
echo AutoComplete::widget([
'name' => 'Company',
'id' => 'ddd',
'clientOptions' => [
'source' => $data,
'autoFill'=>true,
'minLength'=>'4',
'select' => new JsExpression("function( event, ui ) {
$('#user-company').val(ui.item.id);
}")
],
]);
?>
<?= Html::activeHiddenInput($model, 'company')?>
Autocomplete just helps you fill the field with required value.
If you need to submit c_id look to dropdownList or Select2 plugin.
Check this http://demos.krajee.com/widget-details/select2 yii2 widget for ideas.
Here example code:
<?php
use kartik\widgets\Select2;
use app\models\Modelname;
$model = new Modelname;
$data = ['qwe1'=>'color1','key2'=>'color3']
?>
<?= Html::beginForm() ?>
<?= Select2::widget([
'model' => $model,
'attribute' => 'color',
'data' => array_merge(["" => ""], $data),
'options' => ['placeholder' => 'Select a state ...'],
'pluginOptions' => [
'allowClear' => true
],
]); ?>
<?= Html::submitButton('Submit', ['class' => 'btn btn-primary']) ?>
<?= Html::endForm() ?>
It also supports ajax loaded data: http://demos.krajee.com/widget-details/select2#ajax
I wanted to use the Jui Autocomplete so that when I click or focus on autocomplete textbox, it should display options.
I wrote following code and it seems to be working
$floorOptionsArray = ['Basement', 'Ground Floor', 'First floor', 'Second floor', 'Third floor'];
// $floorOptionsArray = array_combine($floorOptionsArray, $floorOptionsArray);
$model = new Customer();
echo $form->field($model, 'floor')
->widget(\yii\jui\AutoComplete::classname(), [
'value' => (!empty($model->floor) ? $model->floor : ''),
'clientOptions' => [
'source' => $floorOptionsArray,
'enabled' => true,
'minLength' => 0
],
'options' =>
[
'placeholder' => 'Floor',
'class' => 'form-control autocomplete-input-bg-arrow ',
'onclick' => "(function ( ) {
$( '#customer-floor' ).autocomplete( 'search', '' );
})();",
'onfocus' => "(function ( ) {
$( '#customer-floor' ).autocomplete( 'search', '' );
})();",
],
])->label(true);

Categories