Setting value of yii2 select2 widget from javascript - php

Is it possible to set certain options as selected in yii2 select2 widget from jquery. The widget is not initialised through js but it is bound to model attribute in form. Any help would be appreciated
Code:
echo $form->field($model, 'news_tags')->widget(Select2::classname(), [
'data' => ArrayHelper::map(app\models\Topics::findAll(['status' => 1]), 'tp_id', 'title'),
'options' => ['multiple' => true, 'placeholder' => 'Select Tags ...'],
'pluginOptions' => [
'tags' => false,
'allowClear' => true
],
])->label(FALSE);
I am trying to use an ajax call and on succes i want to add some tags from clientside.

As is presented in docs https://select2.github.io/examples.html#programmatic
you can use following code:
$("#form-field").val("5").trigger("change");
and it will select option, that has id 5

Related

Yii2 - Stop Field validation if calendar is open

I have a Yii2 active form which includes a field with datepicker. My form is using following attributes:
<?php $form = ActiveForm::begin([
'id' => 'campaign-form',
'enableClientValidation' => true,
'fieldConfig' => [
'options' => ['class' => 'gg-create-group'],
'labelOptions' => ['class' => null],
],
'options' => [
'autocomplete' => 'off',
'enctype' => 'multipart/form-data',
],
]);
?>
I have a field using jquery datepicker, the issue is each time I click on the arrows to navigate through the months in the calendar, client validation is triggered an a error is shown:
I need to stop the error message if the calendar is open and I am using the calendar navigation.
I know I can turn off client validation using:
enableClientValidation => false
But I want to keep client validation. I am wondering if Yii javascript script: $yiiform has an option to do that?
I found a solution. I can use validationOnBlur, if I set it to false on specific field it fixes the issue.
<?php echo $form->field($model, 'client_end_date',
['validateOnBlur' => false])->textInput(['readonly' => 'readonly']); ?>

CakePHP 3 and VueJS - use v-model to set default Form's selectbox

I'm using CakePHP Form helper to create form input fields. When a user edit an item, it will pre-fill the fields with data. I use v-model on each input field to make sure data is correctly populated.
It's all good for the textboxes as data is bound correctly. But for <select> fields, v-model doesn't seem to work. I've tried using default property for the Form->input() but no help. Here's some code:
<div class="fields">
<?= $this->Form->input('email', [
'label' => __('Email'),
'type' => 'email',
'v-model' => 'emailModel',
'placeholder' => __('Required'),
'#keydown.enter.stop.prevent' => 'return false;',
'#keyup.enter.stop.prevent' => 'onSubmit()'
]); ?>
<?= $this->Form->input('status', [
'label' => __('Status'),
'type' => 'select',
'default' => '{{userStatus}}',
'options' => [
1 => 'Active',
2 => 'Inactive'
],
'#keydown.enter.stop.prevent' => 'return false;',
'#keyup.enter.stop.prevent' => 'onSubmit()'
]); ?>
</div>
The email textbox has correct data filled, but not for the status selectbox. But if I replace {{userStatus}} with, for example, 2, it will set the default option to Inactive, even though {{userStatus}} itself has value 2.
How do I go about solving this?
I am new to VueJS but I came across the same question. The VueJS documentation states:
v-model will ignore the initial value, checked or selected attributes found on any form elements. It will always treat the Vue instance data as the source of truth. You should declare the initial value on the JavaScript side, inside the data option of your component.
https://v2.vuejs.org/v2/guide/forms.html#Basic-Usage
Therefore, you need to assign your data.userStatus with your default value.
var vm = new Vue({
el: '#app',
data: {
statusModel: 2 // The default value goes here
}
});
PHP Side:
<div class="fields">
<?= $this->Form->input('email', [
'label' => __('Email'),
'type' => 'email',
'v-model' => 'emailModel',
'placeholder' => __('Required'),
'#keydown.enter.stop.prevent' => 'return false;',
'#keyup.enter.stop.prevent' => 'onSubmit()'
]); ?>
<?= $this->Form->input('status', [
'label' => __('Status'),
'type' => 'select',
'v-model' => 'statusModel',
'options' => [
1 => 'Active',
2 => 'Inactive'
],
'#keydown.enter.stop.prevent' => 'return false;',
'#keyup.enter.stop.prevent' => 'onSubmit()'
]); ?>
</div>
Hope this helps.

Yii2 kartik-v select2 widget allowClear and placeholder not working properly

I'm using the advanced template of Yii2. Whenever the select2 'placeholder' is assigned a value, the widget won't show the initial value. I can work around this by using ['placeholder' => $placeholder] and setting the variable to NULL whenever an initial value exists. However, if the placeholder is NULL and an initial value is showing, then allowClear doesn't work. What am I doing wrong?
View:
use kartik\select2\Select2;
<?= $form->field($profile, 'associationSelect')->widget(Select2::classname(), [
'data' => $associationList,
'language' => 'en',
'theme' => 'krajee',
'options' => ['placeholder' => 'Select Association ...'],
'pluginOptions' => ['allowClear' => true],
])->label(''); ?>
Controller:
$associationArray = Association::find()
->select('association, id')
->indexBy('id')
->orderBy('association')
->all();
$associationList = ArrayHelper::map($associationArray, 'id', 'association');
$associationList is an array like {[1]=>"association1", [2]=>"association2, [3] ..."}.
$profile->associationSelect is prepopulated by the controller with a key. My problem is that the widget always shows 'Select Association ...' whether $profile->associationSelect is populated or not. I only want the placeholder to show if $associationSelect is empty, as that's how a placeholder is supposed to work. And if I leave placeholder empty (NULL), the clear option ("x") shows up in the widget, but won't clear the text (i.e. it doesn't do anything when clicked).
I either didn't completely understand your question or I think I have solved your problem with only a few changes. I have put here several different things so you might not need some of them.
/*
* $profile->associationSelect: data list and assigned default value by key: 2 (third element).
* With this line, your select2 will have a default chosen value from data list.
* Remove this (1) line to show placeholder instead.
*/
if (!empty($associationList)) {
$form->associationSelect = 2;
echo $form->field($profile, 'associationSelect')->widget(Select2::classname(), [
'data' => $associationList,
'language' => 'en',
'theme' => 'krajee',
'options' => [
'placeholder' => $associationList[3] // Placeholder will show 4th element from data list (we do have a list)
],
'pluginOptions' => [
'allowClear' => true
],
]);
} else {
echo $form->field($profile, 'associationSelect')->widget(Select2::classname(), [
'data' => $associationList,
'language' => 'en',
'theme' => 'krajee',
'options' => [
'placeholder' => 'Please select a value' // Placeholder will be default text since we don't have a list.
],
'pluginOptions' => [
'allowClear' => true
],
]);
}
You may choose which option you want (whether with default selected value or just with placeholder). In both cases you can use allowClear and you won't get any errors (if done correctly, of course).
The problem is that 'associationSelect' is an internal attribute rather than a db attribute. I switched to a db attribute and it works just fine.
<?= $form->field($profile, 'association')->widget(Select2::classname(), [
'data' => ArrayHelper::map(Association::find()->orderBy('id')->all(), 'id', 'association'),
'language' => 'en',
'theme' => 'krajee',
'options' => ['placeholder' => 'Select ...',],
'pluginOptions' => ['allowClear' => true],
])->label(''); ?>

Yii2 Select2 widget issue showing unexpected output

Problem :
I was trying to build auto suggestion select box in my yii2 application.I have downloaded from here https://github.com/kartik-v/yii2-widget-select2 and used select2 widget . below is my code
use kartik\select2\Select2;
use app\models\Contact;
use yii\helpers\ArrayHelper;
$data = ArrayHelper::map(Contact::find()->where(['user_id'=>Yii::$app->user->getId()])->orderBy('email')->asArray()->all(), 'id', 'email');
echo $form->field($model, 'contact_id')->widget(Select2::classname(), [
'data' => $data,
'options' => ['placeholder' => 'Search a contact or add new','multiple' => true],
'pluginOptions' => [
'allowClear' => true,
'tags' => true,
'maximumInputLength' => 1000
],
]);
Here contact is model and give array data of email records like test1#gmail.com,test2#gmail.com
but when user search string in dropdownbox it produce output as attachment image
I tried
$this->enableCsrfValidation = false;
in my controller with respective action but no luck,
is there any other solution , i have google an hour but there no solution found

Yii2 Doesn't Get the Value of Disabled Dropdown List or Textfield

I want to disable certain textfields and dropdown lists to prevent user from changing its values. But whenever I try to, it doesn't collect/get the data of that specific disabled textfield or dropdown list.
Here's my view where I display my dropdown lists. It's inside a for loop:
echo $form->field($model1[$i], 'earning_item_id')->widget(Select2::classname(), [
'data' => $earningslistData,
'options' => ['placeholder' => '', 'prevOptionID' => $model1[$i]->earning_item_id, 'prevOptionName' => $earningslistData[$model1[$i]->earning_item_id],
"name" => "EarningDetails[".$i."][earning_item_id]", "row_count1" => $i],
//'disabled' => true,
'pluginOptions' => [
'allowClear' => true,
'label' => false
]
]);
Here's how it looks like without disabling them:
Then, when I save it, it looks like this:
But, when I disable the dropdown lists, it will give me this:
I think the Full Name comes from my model but I don't know why:
public function getFullName()
{
return $this->user ? $this->user->fname . ' ' . $this->user->lname : 'Full Name';
}
It goes the same when I disable a textfield:
echo $form->field($model, 'user_id')->widget(Select2::classname(), [
'data' => $listData,
'options' => ['placeholder' => 'Select a Staff'],
'disabled' => true,
'pluginOptions' => [
'allowClear' => true,
],
])->label('Employee Name');
I am using Kartik widgets for my form fields.
Is there a way to fix this? Please tell me how.
EDIT
Thanks to the commenters below I found out the difference between disabled and readonly. Since it's a dropdown list, here's what I did:
echo $form->field($model, 'user_id')->widget(Select2::classname(), [
'data' => $listData,
'options' => ['placeholder' => 'Select a Staff', ],
'pluginOptions' => [
'allowClear' => true,
],
])->label('Employee Name');
echo $form->field($model, 'user_id')->widget(Select2::classname(), [
'data' => $listData,
'options' => ['placeholder' => 'Select a Staff', 'style' => 'display:none'],
'pluginOptions' => [
'allowClear' => true,
],
])->label('');
Disabled html form field will not submit, the problem is not with yii itself. The solution in this case is to have 2 copies of the same field, one as disabled as you have already included and the other one hidden with the same value as below after the original one.
echo $form->field($model1[$i], 'earning_item_id')->hiddenInput()->label('');

Categories