I'm a new Yii2.I've this bug, I don't know how can I solve this problem.
Bug is very simple templateSelection called two time. this is my code.
if I submit somethings in select2, templateSelection called two time.
echo Select2::widget([
'name' => 'blogId',
'options' => ['placeholder' => 'Search for [![enter image description here][1]][1] ...'],
'pluginOptions' => [
'allowClear' => true,
'minimumInputLength' => 1,
'ajax' => [
'url' => Url::to(['/controller/action']),
'dataType' => 'json',
'data' => new JsExpression('function(params) { return {q:params.term}; }'),
'processResults' => new JsExpression($resultsJs),
],
'templateResult' => new JsExpression($formatRepo),
'templateSelection' => new JsExpression('function(params) { console.log("tst");}'),
],
]);
Thank you for your help.
I've found reponse myself by debuging select2.full.js
problem is right here.
just remove this code. it call two time because it's nested function.
this.$element.on('change.select2', function () { self.dataAdapter.current(function (data) {
//self.trigger('selection:update', {
data: data });
// });
});
Related
i'm trying to use the Kartik Select2 Widget for my Yii2 project.
I'll use the Ajax Loading and everithing works find, but if i set the multiple option it gives me this error.
PHP Warning – yii\base\ErrorException array_combine(): Both parameters
should have an equal number of elements
This error is in Select2.php on this line
$this->data = $multiple ? array_combine((array)$key, (array)$val) : [$key => $val];
i think it's because the data attribute is missing, but if i add data attribute ajax doesn't work properly.
This is my view:
$form->field($model, 'lista_art')->widget(Select2::classname(), [
'initValueText' => "", // set the initial display text
//'data' => '',
'options' => ['placeholder' => 'Select a color ...',
//'multiple' =>true, // error here
],
'pluginOptions' => [
'tags' => true,
'tokenSeparators' => [',', ' '],
'allowClear' => true,
'minimumInputLength' => 3,
'language' => [
'errorLoading' => new JsExpression("function () { return 'Waiting for results...'; }"),
],
'ajax' => [
'url' => \yii\helpers\Url::to(['lista-articoli']),
'dataType' => 'json',
'data' => new JsExpression('function(params) { return {q:params.term}; }')
],
'escapeMarkup' => new JsExpression('function (markup) { console.log(markup);return markup; }'),
'templateResult' => new JsExpression('function(lista_art) { return lista_art.art_modello; }'),
'templateSelection' => new JsExpression('function (lista_art) { return lista_art.art_modello; }'),
],
]);
Also tried to insert multiple option inside 'pluginOptions' array but doesnt work.
Is it possible to use multiple option with Ajax Loading?
P.s. I've check my developer toolbar and the response is correct, and gives me what i've expected.
You forgot to set data attribute
Sample how to use kartik select 2 with model and active form
$model->keywords = [1, 2]; // NOTE THIS IS AN ARRAY of keys
$form->field($model, 'keywords')->widget(Select2::className(), [
'pluginOptions' => [
'tags' => true,
'multiple' =>true,
],
'data' => [1=>'keyword1', 2=>'keyword2', 3=>'keyword3'],
])
Update
Try to set up data as empty array like
'data' => []
i've some troubles with Select2 kartik plugin for yii2.
I set up my plugin with Ajax Loading and, in my create view works fine, so i can select multiple value and save it on database.
When i show the update view i want to set visible the value that i've saved in my database but it show me only a gray rectangle with x icon.
This is what i've tried.
echo $form->field($model, 'lista_art')->widget(Select2::classname(), [
'initValueText' => $art_list,// array of text to show in the tag for the selected items
'showToggleAll' => false,
'options' => ['placeholder' => 'Select...',
'multiple' =>true,
'value' => $value, // array of Id of the selected items
],
'pluginOptions' => [
'tags' => true,
'tokenSeparators' => [',', ' '],
'allowClear' => true,
'minimumInputLength' => 3,
'language' => [
'errorLoading' => new JsExpression("function () { return 'Waiting for results...'; }"),
],
'ajax' => [
'url' => \yii\helpers\Url::to(['lista-articoli']),
'dataType' => 'json',
'data' => new JsExpression('function(params) { return {q:params.term}; }')
],
'escapeMarkup' => new JsExpression('function (markup) { console.log(markup);return markup; }'),
'templateResult' => new JsExpression('function(lista_art) { return lista_art.art_modello; }'),
'templateSelection' => new JsExpression('function (lista_art) { return lista_art.art_modello; }'),
],
]);
And this is the result.
$art_list and $value are array's like this
$art_list = ['name1','name2'];
$value= ['id_name1','id_name2'];
If i inspect the code with browser inspector i find this
<li class="select2-selection__choice" title="name1">
<span class="select2-selection__choice__remove" role="presentation">×</span>
</li>
UPDATE
I'll find the error, and it is very trivial..
The error is here
'templateResult' => new JsExpression('function(lista_art) { return lista_art.art_modello; }'),
'templateSelection' => new JsExpression('function (lista_art) { return lista_art.art_modello; }')
There is no lista_art.art_modello because the object for this element is inthe format id:id_name1 and text:name1 so changing the code like this it will work
'templateResult' => new JsExpression('function(lista_art) { return lista_art.text; }'),
'templateSelection' => new JsExpression('function (lista_art) { return lista_art.text; }')
Hi guys thanks for responding me.
I found a solution for my problem and i'll post an answer for anyone who get same problem.
This is my Select2 Field in my view:
echo $form->field($model, 'lista_art')->widget(Select2::classname(), [
'initValueText' => $art_list,// array of text to show in the tag for the selected items
'showToggleAll' => false,
'options' => ['placeholder' => 'Seleziona un prodotto',
//'tags' => true,
'multiple' =>true,
'value' => $value, // array of Id of the selected items
'class' => 'validatej'
],
'pluginOptions' => [
'tags' => true,
'tokenSeparators' => [',' , ' '],
'allowClear' => true,
'minimumInputLength' => 3,
'language' => [
'errorLoading' => new JsExpression("function () { return 'Waiting for results...'; }"),
],
'ajax' => [
'url' => \yii\helpers\Url::to(['lista-articoli']),
'dataType' => 'json',
'data' => new JsExpression('function(params) {return {q:params.term}; }')
],
'escapeMarkup' => new JsExpression('function (markup) { return markup; }'),
'templateResult' => new JsExpression('function(data) {return data.text; }'),
'templateSelection' => new JsExpression('function (data) { return data.text; }'),
],
]);
The problem isn't here but in the function called by ajax
public function actionGetArt($q = null, $id = null) {
\Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;//restituisco json
$out = ['results' => ['id' => '', 'text' => '']];
if (!is_null($q)) {
$query = new Query;
$query->select('art_cod AS id, art_modello AS text')
->from('art')
->where(['ilike', 'art_modello', $q]);
$command = $query->createCommand();
$data = $command->queryAll();
$out['results'] = array_values($data);
}
elseif ($id > 0) {
$out['results'] = ['id' => $id, 'text' => Catalogo::find($id)->art_modello];
}
return $out;
}
In the line where i call select Sql
$query->select('art_cod AS id, art_modello AS text')
you have to set your id table an your text table(in my case art_modello) AS id and AS text accordly with the select2 widget. This is not specified in the docs so i'll have read the code and found this solution.
You can't set initValueText as an array.
See docs:
initValueText: string, the text to displayed in Select2 widget for the initial value. This is useful and applicable when you are using the widget with ajax loaded data AND/OR you are not providing the data. Check the ajax usage section for an example.
'initValueText' => $art_text, // set the initial display text
Use data instead:
'data' => $art_list,
I need to load data with ajax to a Kartik Select2 but only when certain input changes values. Kind of like...
<?= $form->field($model, 'id_list')->widget(Select2::classname(), [
'data' => [],
'theme' => Select2::THEME_BOOTSTRAP,
'options' => [
'placeholder' => 'List',
],
'pluginOptions' => [
'allowClear' => true,
'action' => '#input_first'.change // or something
'ajax' => [
'url' => Url::to(['/list']),
'dataType' => 'json',
'data' => new JsExpression('function(params) { return {q:params.term}; }')
],
],
]);?>
Have you tried to use Select2 with DepDrop plugin (http://demos.krajee.com/widget-details/depdrop)?
I have this little problem in uploading multiple images using yii2 and Kartik fileInput extension.
this is the model:
public $file;
public static function tableName()
{
return 'news';
}
public function rules()
{
return [
[['news_desc', 'news_context', 'news_first_source', 'news_second_source', 'news_third_source', 'news_responsibe_party', 'news_first_testimony', 'news_second_testimony', 'news_body', 'news_lang'], 'string'],
[['news_gov_id', 'news_typ_id', 'news_is_in_slider', 'news_is_act', 'news_is_del'], 'integer'],
[['news_happened_date', 'news_created_date', 'file'], 'safe'],
[['news_typ_id', 'news_lang'], 'required'],
[['news_title'], 'string', 'max' => 255],
[['file'], 'file','maxFiles' => 6],
];
}
as you can notice I am using maxFiles but it didnt worked for me
Controller:
public function actionCreate_news()
{
$model = new News();
if ($model->load(Yii::$app->request->post())) {
$model->file = UploadedFile::getInstances($model, 'file');
var_dump($model->file);
die();}}
right now I am just var dump the files I get but the problem there is only one file not all the files i uploaded
view:
echo FileInput::widget([
'model' => $model,
'attribute' => 'file[]',
'name' => 'file[]',
'options' => [
'multiple' => 'true',
'accept' => 'image/*'
],
'pluginOptions' => [
'showCaption' => false,
'showRemove' => false,
'showUpload' => false,
'allowedFileExtensions' => ['jpg','jpeg','png'],
'overwriteInitial' => false
],
]);
i have read all things about this issue and tried all the possible solutions but the problem is still there
when i press submit for the form only the last file will be submited
thanks
Remove 'name' => 'file[]', from this widget also single quotes from true.
echo FileInput::widget([
'model' => $model,
'attribute' => 'file[]',
'options' => [
'multiple' => true,
'accept' => 'image/*'
],
'pluginOptions' => [
'showCaption' => false,
'showRemove' => false,
'showUpload' => false,
'allowedFileExtensions' => ['jpg','jpeg','png'],
'overwriteInitial' => false
],
]);
Original:
echo FileInput::widget([
'model' => $model,
'attribute' => 'attachment_1[]',
'options' => ['multiple' => true]
]);
Thank you all I figured out the solution for my question i was trying to upload the images when submitting the form but it turned that i was wrong so i used the widget to upload the images using ajax like in here:
http://webtips.krajee.com/ajax-based-file-uploads-using-fileinput-plugin/
then using the plugin event i took the names of files to save in the DB when the form submited
I've a question about yii2 kartik-v widget select 2.
the widget is attached to a field in my view
<?=
$form->field($model, 'address')->widget(Select2::className(), [
'options' => ['placeholder' => 'Inserta an address '],
'pluginOptions' => [
'allowClear' => true,
'minimumInputLength' => 3,
'ajax' => [
'url' => Url::to(['register/addresses']),
'dataType' => 'json',
'data' => new JsExpression('function(params) { return {q:params.term}; }')
],
'escapeMarkup' => new JsExpression('function (markup) { return markup; }'),
'templateResult' => new JsExpression('function(address) { return address.name; }'),
'templateSelection' => new JsExpression('function (address) { return address.name; }'),
],
'pluginEvents' => [
"select2:select" => "function(e) {
// some function
}",
],
]);
?>
if in my controller i want to set to this field a value
like: $model->address = "Some Value"; on the view the field remain blank
what can i do?
UPDATE!
As the documentation say i can use the option: 'initValueText' if i use the ajax version of this plugin. So i've tried to set 'initValueText' => $model->address, but the result is the same
hey i had the same issue with #ajax neither placeholder nor initValueText were showing
what i did was this
<?php
$product = $model->product_id ? Product::findOne($model->product_id)->name : 'select ....';
echo $form->field($model, 'product_id')->widget(Select2::classname(), [
'initValueText' => $product, // set the initial display text
// 'options' => ['placeholder' => 'select ....'],
'pluginOptions' => [
'allowClear' => true,
'minimumInputLength' => 3,
'ajax' => [
'url' => Url::to(['list']),
'dataType' => 'json',
'data' => new JsExpression('function(params) { return {q:params.term}; }')
],
'escapeMarkup' => new JsExpression('function (markup) { return markup; }'),
'templateResult' => new JsExpression('function(product_id) { return product_id.name; }'),
'templateSelection' => new JsExpression('function (product_id) { return product_id.name; }'),
],
]);?>
if the model is new 'select ....' is shown else the product's name
since "options" is not doing much either
hope this will be hopeful to someone
The problem was this:
'escapeMarkup' => new JsExpression('function (markup) { return markup; }'),
'templateResult' => new JsExpression('function(address) { return address.name; }'),
'templateSelection' => new JsExpression('function (address) { return address.name; }'),
It seems that this plugin want a specific return for the keys 'templateResult' and 'templateSelection'.
I've modified the JsExpression return value with address.text (instead of adress.name) as the guide examples : Link.
And then i've modified also the PHP method that return the results:
public function actionAddresses($q = NULL, $id = NULL)
{
Yii::$app->response->format = Response::FORMAT_JSON;
$results = array();
if (!is_null($q)) {
$geocoder = new GeocodingClient();
$request = $geocoder->lookup(['address' => $q]);
$counter = 1;
foreach ($request['results'] as $key => $value) {
$results['results'][] = [
'id' => $counter,
'text' => $value['formatted_address'], // Instead of 'name'
'coordinate' => $value['geometry']['location']
];
$counter++;
}
}
return $results;
}
I hope this may help someone with a similar problem.
Its bit late.. but i too had same problem.. i resolved it by assigning value
<?=
$form->field($model, 'address')->widget(Select2::className(), [
'initValueText' => $model->address,
'value' => $model->address,
'options' => ['placeholder' => 'Inserta an address '],
'pluginOptions' => [
'allowClear' => true,
'minimumInputLength' => 3,
'ajax' => [
'url' => Url::to(['register/addresses']),
'dataType' => 'json',
'data' => new JsExpression('function(params) { return {q:params.term}; }')
],
'escapeMarkup' => new JsExpression('function (markup) { return markup; }'),
'templateResult' => new JsExpression('function(address) { return address.name; }'),
'templateSelection' => new JsExpression('function (address) { return address.name; }'),
],
'pluginEvents' => [
"select2:select" => "function(e) {
// some function
}",
],
]);
?>
you use kartik select2, in controller you have set a value (id/ids) and name values for 'initValueText'
$model->id = 1; // or if arrays [1,3,4,5]
$username = User::find()->select('name')->where('id' => $model->id)->scalar();
and in view kartik select2
$form->field($model, 'username')->widget(Select2::className(), [
'initValueText' => $username;
...
I was facing same problem. Then I tried value key into the options and it worked.
<?php
echo $form->field($model, 'test')->widget(Select2::classname(), [
//'data' => ['test', 'test2'],
'initValueText'=>['test','test2'],
'options' => ['multiple' => true, 'value'=>['1','2']],
'pluginOptions' => [
'multiple' => true,
'allowClear' => true,
'minimumInputLength' => 1,
'language' => [
'errorLoading' => new JsExpression("function () { return 'Waiting for results...'; }"),
],
'ajax' => [
'url' => '...',
'dataType' => 'json',
'data' => new JsExpression('function(params) { return {q:params.term}; }')
],
'escapeMarkup' => new JsExpression('function (m) { return m; }')
?>
Hope It'll be helpful for someone.
I fix this solution by using trigger function. In below method we can set default value in kartik select2 widget.
$('#id').val(11).trigger('change'); //in val() mention the hash value of your select2 list