I have a yii2 activeform where the functionality of the form can change based on other things within the form. So, I have a clubs field, that can be multiple in some instances but not multiple in others.
<?= $form->field($model, 'clubs')->widget(\kartik\widgets\Select2::classname(), [
'data' => $club_data,
'hideSearch' => false,
'options' => ['placeholder' => 'Add Club(s)'],
'pluginOptions' => [
'allowClear' => true,
'multiple' => true,
'minimumInputLength' => 3,
'ajax' => [
'url' => 'web/index.php?r=clubs/clubslist',
'dataType' => 'json',
'data' => new JsExpression('function(params) { return {q:params.term}; }'),
],
],
])->label('Club(s)'); ?>
I need to programmatically change the multiple pluginOption to true and false. This should be when the user goes into the form but also immediately when a dropdown is changed on the form. I can do it when the user initially goes into the form but not immediately when another dropdown is changed.
I've made separate fields, one actually linked to a field in the database and another not, this kind of works but it's far from elegant!
I've looked in both the kartik select2 documentation and the standard jquery select2 documentation and I can't spot anything. Any help or pointers would be much appreciated.
Reference
I was working on a Yii2-formwizard plugin a few months back where I had a situation of providing tabular functionality and cloning the fields really became the pain in the ass when it came to using 3rd party plugins like Select2 and Datepicker and I figured out the following code along with a lot of other (as the other part isn't relevant to your problem so not adding it).
Approach to the problem
The way Kartik-select2 works it stores the select2 plugin-specific options in the data-krajee-select2 attribute of the element you are using the select2 on.
And the theme or say the Kartik's plugin-specific options like theme and others are saved in the variable whose name is saved in the data-s2-options attribute. You can look for both of them in view-source of the page where you are using it.
Solution
So what you need to do is to
Steps
Get the applied options
Add/Update the option
Apply back the options
As you just added a single field and not the other one on who's selection it would change, I would demonstrate an example where you can change the behavior of the select2 from multiple to single using 2 different buttons, clicking on the relevant button the select2 will work accordingly. You can adjust the javascript code where ever you want to.
But before I add any code you need to fix one thing, you don't need the main data option when you are using the ajax option inside the plugin options. In other words, it does not have any effect on your select2 and is adding page load time only you should remove it.
You select2 should look like below, I added id to the options of the select2 for the example you can change it to the active form formatted name like model-field_name format if you like, but don't forget to change the id in the javascript code too
<?php echo $form->field($model, 'clubs')->widget(\kartik\widgets\Select2::classname(), [
'hideSearch' => false,
'options' => ['placeholder' => 'Add Club(s)','id'=>'clubs'],
'pluginOptions' => [
'allowClear' => true,
'multiple' => true,
'minimumInputLength' => 3,
'ajax' => [
'url' => 'web/index.php?r=clubs/clubslist',
'dataType' => 'json',
'data' => new JsExpression('function(params) { return {q:params.term}; }')
]
]
])->label('Club(s)');?>
Add the following buttons on your page
echo Html::button('multiple', ['class' => 'btn btn-info', 'id' => 'multi']);
echo Html::button('single', ['class' => 'btn btn-info', 'id' => 'single']);
And now the magic thing, add it on the top of your view
$js = <<<JS
var element=$("#clubs");
$('#multi').on('click',function(e){
//reset select2 values if previously selected
element.val(null).trigger('change');
//get plugin options
let dataSelect = eval(element.data('krajee-select2'));
//get kartik-select2 options
let krajeeOptions = element.data('s2-options');
//add your options
dataSelect.multiple=true;
//apply select2 options and load select2 again
$.when(element.select2(dataSelect)).done(initS2Loading("clubs", krajeeOptions));
});
$('#single').on('click',function(e){
element.val(null).trigger('change');
let dataSelect = eval(element.data('krajee-select2'));
let krajeeOptions = element.data('s2-options');
dataSelect.multiple=false;
$.when(element.select2(dataSelect)).done(initS2Loading("clubs", krajeeOptions));
});
JS;
$this->registerJs($js, \yii\web\View::POS_READY);
Now if your select2 is working correctly click on the multiple button and you will see the multiple selections are enabled for the select2 and when clicked on the single button.
Hope it helps.
Related
Is there an option or a known way to display collection form on page load instead of clicking on "add" button in order to display it ?
I trigger a click event on page load but its not the expected behavior..
Any help would be much appreciated.
Alright, I achieved what I wanted by setting a default collection array on my form field, each Entity object in array imbricates a form, since I needed to display 3 form on page load I instanciated 3 entity, quite logic when I think of it now but a dedicated option could be nice though.
->add('details', CollectionType::class, [
'data' => [new OfferDetail(), new OfferDetail(), new OfferDetail()],
'label' => false,
'required' => true,
'type_options' => [
'delete' => false,
],
], [
'edit' => 'inline',
'inline' => 'table'
])
Hi i am using kartik select2 in my yii application. The select box for selecting multiple options is working fine. However i am facing one small issue.
Like if i type ba then it will display all matching options. but when i press enter then Bakam get selected but the text ba remains in select box. It should get removed.
Here is code for my select box
<?= $form->field($model, 'area')->widget(Select2::classname(), [
'data' => [],
'options' => ['placeholder' => 'Select Location'],
'pluginOptions' => [
'closeOnSelect' => false,
'tags' => false,
'multiple' => true,
],
])->label("Reassign Location")
?>
I checked it on kartik website the code seems fine then why the text remains there?
Set 'closeOnSelect' => true, in pluginOptions to remove selected option.
I am using the search plugin for CakePHP 3 from FriendsOfCake and I am trying to search for select options.
View:
echo $this->Form->input('worker_id', [
'multiple' => true,
'options' => $workers,
'label' => ['text' => __('Worker: ')],
]);
Table:
$this->searchManager()
->add('worker_id', 'Search.Value');
Now whenever I select an option in the view, it appends %5B0%5D to the url which stands for [0], e.g.
http://localhost/customers?worker_id%5B0%5D=23
When I remove %5B0%5D from the url, the correct results are shown. How can I prevent this from being added to the url automatically?
I have a typical Yii2 form for updating my model with a typical submit button. Next to it, I have a "Delete photo" button, that appears, if there is any photo to delete. The piece of view looks like that:
<?= Html::submitButton('Save changes', ['class' => 'btn btn-primary', 'name' => 'edit-button']) ?>
<?php $image = isset($page->photo) ? $page->photo->getImageUrl() : null; ?>
<?php if (isset($image)): ?>
<?= Html::a('Delete photo', ['delete-image', 'lab' => $lab->id, 'kind' => $page->kind], [
'class' => 'btn btn-danger',
'data' => [
'confirm' => 'Do you really want to delete this photo?',
'method' => 'post'
],
]) ?>
<?php endif; ?>
When there is a photo attached to this model and these two buttons appear next to each other, I must comment out 'method' => 'post' part in second button code. Because, if I don't this this, the second button is... submitting the form (just like the first one) instead of calling lab/delete-image route.
This is the first thing, that I don't understand. The entire code is either generated by Gii or copy-pasted from some Yii tutorials. Not even a bit of my invention and yet it works strangely. What am I missing?
It seems, that normal Html::a link (only styled by Twitter Bootstrap to look like a button, but not being a button at all) is submitting a form, instead of calling its action, when it contains data-method="post" attribute in element code. Is this a bug in Yii2 or am I missing something?
You need to place the link outside of the form. For calling actions from elements with data-method attribute yii has js function handleAction, and its documentation says:
This method recognizes the data-method attribute of the element. If the attribute exists, the method will submit the form containing this element. If there is no containing form, a form will be created and submitted using the method given by this attribute value (e.g. "post", "put").
For hyperlinks, the form action will take the value of the "href" attribute of the link.
Also if you use yii2 v2.0.3 or higher you can add data-params attribute which value should be JSON representation of the data, and this data will be submitted in request. As example:
echo Html::a('Delete image', ['delete-image'], [
'data' => [
'confirm' => 'Do you really want to delete this photo?'
'method' => 'post',
'params' => [
'lab' => $lab->id,
'kind' => $page->kind,
],
],
]);
In this example params array will be json encoded by yii2 internaly
I have a gridview(admin.php) of test table. Here, I have two colums Contact Approval and Greetings Approval. I need to put two radio buttons ('Contact' and 'Greetings')in admin page. When I click on 'Contact' radio button all the columns except for Greetings Approval should be displayed in gridview and When I click on 'Greetings' radio button all the columns except for Contact Approval should be displayed in gridview. The update.php should also have the same effect.i.e when I click on edit option the update.php should have the fields based on the radiobutton data.How can I do this.
Below is the code of radiobuttonlist
<div class="ContactGreetingGroup">
<?php echo CHtml::radioButtonList('approval','',array('0'=>'Greetings Approval','1'=>'Contact Approval'),array(
'labelOptions'=>array('style'=>'display:inline'),
'onclick' => 'this.form.submit()',
'separator'=>''));
?>
</div>
CDataColumn has a 'visible' property. You just need to set it depending on your parameter.
$approval = Yii::app()->request->getParam('approval');
'columns'=>[
[
'name' => 'greetings',
'visible' => ($approval)? false : true,
],
[
'name' => 'contact',
'visible' => ($approval)? true : false,
],
],
As for changing the behavior of the edit button, (since you need a parameter to say if you want "contact-mode" or "greetings-mode") You must overwrite the view-buttons url property.
[
'class'=>'CButtonColumn',
'buttons'=>[
'view' => [
'url'=>'Yii::app()->createUrl(
"Something/Update",
["id"=>$data->id, "approval"->$approval ])',
],
],
],
After that you need to make a similar check in your update.php (_form.php) to decide what to display.
if( $approval ) :
....
Added:
If your radiobuttonlist is inside form-tags, you can submit it like this:
<form> <!-- You need a form to use form.submit! -->
<?php echo CHtml::radioButtonList('approval','',
array('0'=>'Greetings Approval','1'=>'Contact Approval'),
array('labelOptions'=>array('style'=>'display:inline'),
'onclick' => 'this.form.submit()', // Added this.
'separator'=>'')
); ?>
</form>
I also edited the above code to match your variable names. I haven't tested it, but it should give you an idea I hope.