Autocomplete in yii2 - php

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);

Related

Can not set placeholder for DateRangePicker::widget

I have following widget in my yii2 application
<?= DateRangePicker::widget([
'model'=>$model,
'attribute' => 'fact_close_date_range',
'options'=>[
'placeholder'=>'Фактическая дата закрытия займа',
'class'=> 'ui input',
'id'=> 'fact_close_date_range'
],
'useWithAddon'=>false,
'convertFormat'=>true,
'presetDropdown'=>false,
'hideInput'=>false,
'pluginOptions'=>[
'opens' => 'right',
'locale'=>[
'format' => 'Y-m-d'
],
],
]);
?>
but on initial load what I am getting is input where two dates is set for today. For example 17.03.2021 - 17.03.2021, and should be my placeholder Фактическая дата закрытия займа like so. Documentation of kartik doesn't describe such things
try this :
<?= DateRangePicker::widget([
'name'=>'date_range_2',
'presetDropdown'=>true,
'convertFormat'=>true,
'value' => $model->date_range,
// 'includeMonthsFilter'=>true,
'pluginOptions'=> ['locale' => ['format' => 'Y-m-d']],
'options' => ['id'=> 'tgl-search', 'class' => 'invoice-search','placeholder' => 'Select range...']
]);

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

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

Yii2, Set multiple Value Select2

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

Yii2 Autocomplete : Save the ID instead of value

I have a list of array called as datalist which contains the name of companies with id.when i use it with the typeahead widget,it captures the value of company with the variable coSearch(id of input).but i want to display the list of companies and when selected,it must give the vale of that id in variable .i am really messed with this problem working from three days.Please help me out.
Here is the code for my activeform which contains the widget.
<?php
$form = ActiveForm::begin([
'action' => ['search'],
'method' => 'get',
]);
$dataList=ArrayHelper::map($companies, 'id', 'name');
echo Typeahead::widget([
'model' => $companySearched,
'name'=>'coSearch',
'options' => ['placeholder' => 'Search company','id'=>'searchCompany1','class' => 'form- control','value'=>'1'],
'pluginOptions' => ['highlight'=>true],
'dataset' => [
[
'local' => $dataList,
'limit' => 10,
]
]
]);
?>
This can be solved with the help of a hidden field.I use autocomplete here
<?php
use yii\web\JsExpression;
use yii\jui\AutoComplete;
$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 ) {
$('#model-company').val(ui.item.id);
}")],
]);
?>
<?= Html::activeHiddenInput($model, 'company')?>
Hope this help!

Categories