I'm using knockout js and the chosen plugin (https://github.com/harvesthq/chosen) to try and make a good looking multi select.
I've tried various ways but can't get the multiselect to work with the data I'm using. When I click on the multiselect, no values are shown even though the options binding contains the correct data.
HTML:
<select multiple="multiple" data-bind="options: allCustomers,
selectedOptions: event().customers, optionsText: 'name',
optionsValue: 'id', chosen: true " ></select>
Simplified version of the view model:
function Event()
{
this.customers = ko.observableArray();
};
//for chosen plugin
ko.bindingHandlers.chosen = {
update: function(element, valueAccessor, allBindingsAccessor, viewModel) {
$(element).chosen();
}
}
function ViewModel()
{
this.event = ko.observable(new Event());
this.allCustomers = ko.observableArray();
};
var viewModel = new ViewModel();
$.getJSON("/get_json", function(data)
{
for (var c = 0; c < data.customers.length; c++)
{
viewModel.allCustomers.push(data.customers[c]);
}
});
ko.applyBindings(viewModel);
PHP:
function get_json()
{
$eventData = array(
'customers' => array(array('name' => 'Bob', 'id' => 1), array('name' => 'John', 'id' => 2)),
'moreData' => array(),
'evenMoreData' => array()
);
echo json_encode($eventData);
}
This shows the chosen styled select box but when I click in it, no options appear.
When I create a local JS array in the view model for the customers and pass that into allCustomers, the multiselect works correctly (see my jsfiddle) so it's something to do with getting data from the server, but I've been staring at this a while and can't see the problem!
Any help much appreciated
I found the problem after #Tyrsius suggested it might not be updating the data after the initial binding.
I added $(element).trigger("liszt:updated"); to the custom binding like so:
ko.bindingHandlers.chosen = {
update: function(element, valueAccessor, allBindingsAccessor, viewModel) {
$(element).chosen();
$(element).trigger("liszt:updated");
}
}
The code in the accepted version for some reason did not work for me. Probably because the liszt:updated command does not trigger chosen to be updated. Based on docs here I wrote my own version:
ko.bindingHandlers.chosen = {
init: function (element, valueAccessor, allBindingsAccessor, viewModel) {
$(element).chosen({ width: "95%", placeholder_text_multiple: "Select..." });
var value = ko.unwrap(valueAccessor());
},
update: function (element, valueAccessor, allBindingsAccessor, viewModel) {
var value = ko.unwrap(valueAccessor());
$(element).trigger("chosen:updated");
}
}
Related
I'm now working with select2 drop-down plugin. I came situation that I have to add a select2 field which auto populate the existing mail id's in our app. I was able to do so, but I also has to add new mail id's which are not in our app in same field. I do not able work it out. Can any of you please help me out from this...
Here is my view page code.
<input type="hidden" class="select2 to_email w-100" name="to_email[]"
data-role="to_email" data-width="100%" data-placeholder="To" value="">
Js code:
$('body').on('click','[data-button="reply-mail"],[data-click="reply"]', function() {
attach = [];
var $ti = $(this).closest('[data-role="row-list"]').find('[data-role="reply-mail-wrap"]');
var $to_this = $ti.find('[data-role="to_email"]');
var mail_toadr = $ti.find('input[name="to_addr"]').val();
$($to_this).select2({
placeholder: "Search for a contact",
minimumInputLength: 3,
//maximumSelectionLength: 1,
multiple : true,
ajax: {
url: Utils.siteUrl()+'mailbox/get_all_contacts',
type: 'POST',
dataType: 'json',
quietMillis: 250,
data: function (term, page) {
return {
term: term, //search term
page_limit: 100 // page size
};
},
results: function (data, page) {
return { results: data};
}
},
initSelection: function(element, callback) {
return $.getJSON(Utils.siteUrl()+'mailbox/get_all_contacts?email=' + (mail_toadr), null, function(data) {
return callback(data);
});
}
});
});
I know, working example could be better to you, but I'm sorry, I do not know how to do it.
A screen shot for small help:http://awesomescreenshot.com/08264xy485
Kindly help..
I have got a fix for my requirement. If we enter a non-existing value in our field, results: function (data, page) {...} returns an empty array. We can check this as:
results: function (data, page) {
for (var obj in data) {
id = JSON.stringify(data[obj].id);
text = JSON.stringify(data[obj].text);
if (id == '"0"') {
$ti.find('.to_email').select2('val', '<li class="select2-search-choice"><div>'+ text +'</div><a tabindex="-1" class="select2-search-choice-close" onclick="return false;" href="#"></a></li>');
}
}
return { results: data};
}
But, better than this I suggest you to do a check in the area where we fetch result (here: Utils.siteUrl()+'mailbox/get_all_contacts'). I have done this to fix my issue:
function get_all_contacts()
{
// $contacts is the result array from DB.
// $term is the text to search, eg: 111
foreach($contacts as $contact_row) {
$contact_all[] = array('id' => $contact_row['id'], 'text' => $contact_row['primary_email']);
}
if (empty($contact_all)) {
$contact_all = array('0' => array('id' => 'undefinedMAILID_'. $term, 'text' => $term ) );
}
$contact_data['results'] = $contact_all;
send_json_response($contact_all);
}
Getting value in JS:
sel_ids = $('.to_email').select2('val');
console.log(sel_ids);
// console will show - ["value if mail id is existing", "undefinedMAILID_111"]
hope this will help someone.
I am using kartik select2 widget in my yii2 basic app. now i have to display province names in select2 widget on ajax call. It is working fine if i put it directly in form. however not working with ajax call.
Here are my form fields:
<?= $form->field($model, 'role')->dropDownList(
ArrayHelper::map(SubAdminRoles::find()->all(), 'id', 'role_name'),
[
'prompt' => 'Select Role',
'onchange' => '
if($(this).val() != 3) {
$( "#user_area" ).html("showLoading");
$.post( "fetch-area-list?id='.'"+$(this).val(),
function(data) {
$( "#user_area" ).html(data);
})
}'
]
) ?>
<div id="user_area">
</div>
And here is my action code
public function actionFetchAreaList($id) {
// $this->layout = 'none';
$data = [];
if($id == 1) {
$provinceList = \app\modules\adminpanel\models\ProvinceMaster::findAll(['status' => 1, 'is_deleted' => 0]);
foreach($provinceList as $obj) {
$data[$obj['id']] = $obj['province_name'];
}
//print_r($data);
//exit;
} else if($id == 2) {
$subDistrictList = \app\modules\adminpanel\models\SubDistrictMaster::findAll(['status' => 1, 'is_deleted' => 0]);
foreach($subDistrictList as $obj) {
$data[$obj['id']] = $obj['sub_district_name'];
}
}
echo '<label class="control-label">Select Province</label>';
echo Select2::widget([
'name' => 'state_2',
'value' => '1',
'data' => $data,
'options' => ['multiple' => true, 'placeholder' => 'Select Province']
]);
exit;
}
now when i try to get it through ajax i comes with display:none property so i am not able to show my select2 box.
I Also tried changing display:none to display:block in select2 class. In that case i got the select box, but is simple html multiple select box not select2 widget.
How to get it from controller using ajax call?
Thanks in advance.
It is bad practice to render html inside action.
In your case widget requires related JS for initialization. But it will not include in your response.
Move all your html to view area-list and render using following code:
public function actionFetchAreaList($id) {
$this->layout = false;
// ... preparing data
return $this->renderAjax('area-list', [
// ... some view data
]);
}
Method renderAjax renders a named view and injects all registered JS/CSS scripts and files. It is usually used in response to AJAX Web requests.
I also have similar project like this.
I have 2 combobox (using select2). When select a district from the first combobox. It will call an ajax request to get province list and fill into the second combobox.
Here is my solution:
Using Select2 widget as normally in form
Using javascript to call ajax request and change data of the second combobox.
My controller response data in json format.
$('#district-selector').on('change', function() {
var districtId = $(this).val();
var url = $(this).attr('tb_href');
$('#province-selector').html('');
$.get(
url,
{
city_id: districtId
},
function(response) {
if (response.error == 0 && response.data.length) {
$('#province-selector').append(new Option('', ''));
$.each(response.data, function() {
console.log(this.id + '--' + this.title);
var newOption = new Option(this.title, this.id);
$('#province-selector').append(newOption);
});
}
$('#province-selector').trigger('change');
}
);
});
Demo: demo link
I had created basic custom module. in that i just filled information form and that information will stored into the database. and that data i am showing into table format. now i want to edit and delete records from clicking links.
I want to call php function on clicking following links
links are:
while($data = $result->fetchObject()){
$rows[] = array(
$data->id,
$data->name,
$data->address,
$data->mob,
$data->gen,
$data->email,
$data->hob,
l('Edit' .$data->id,'/table', array('query' => array('edi'=>$data- >id))),
l('Delete' .$data->id, '/table', array('query' => array('del'=>$data->id))),
);
}
and the functions are as follows:
function form_values_edit($id){
$id_val = $id;
$my_object = db_select('demo_forms','n')
->fields('n')
->condition('id', $id_val )
->execute()
->fetchAssoc();
return drupal_get_form('demo_form', $my_object);
}
function delete_confirm($form, &$form_state, $id){
$form['delete'] = array(
'#type' => 'value',
'#value' => $id,
);
return confirm_form(
$form,
t('Are you sure you want to delete this?',
'/table',
t('This action cannot be undone'),
t('Delete'),
t('Cancel')
));
}
function delete_confirm_submit($form, &$form_state) {
$record = $form_state['values']['delete'];
if ($record ) {
$num_deleted = db_delete('demo_forms')
->condition('id', $record )
->execute();
drupal_set_message('The record has been deleted!');
}
$form_state['redirect'] = "/table";
}
Thanks
You cannot call a PHP function dynamically by clicking a link, as PHP is a server side language. HOWEVER if you load another page, before loading the page you can execute PHP code.
EDIT
if you need a PHP function dynamically, what I usually do (and this may be wrong according to some people) is call that function in an AJAX call. Note: I would generally use POST for this.
$.ajax(
url: 'url/to/php/function',
type: 'POST/GET',
data: {'data' : data},
success: function(res) {
// use the result stored in res
},
error: function(res) {
// use res to get the error result
}
);
Just add check for id field or another unique value in your php code and update or delete rows where id = ... With out unique value you can't do that. Describe your usability and post your html for more...
I use the following select2 Yii widget in my view to populate a drop-down list. Since the data necessary for the preparation of the select list consists of more than 2K records I use select2 with minimumInputLength parameter and an ajax query to generate partial result of the list based on user input. If I create a new record I have no problem at all. It populates everything fine and I can save data to my database. However I don't know how to load saved data back to this drop-down during my update action. I read somewhere that initselection intended for this purpose but I couldn't figure out how to use it.
Can someone help me out on this?
My view:
$this->widget('ext.select2.ESelect2', array(
'selector' => '#EtelOsszerendeles_osszetevo_id',
'options' => array(
'allowClear'=>true,
'placeholder'=>'Kérem válasszon összetevőt!',
'minimumInputLength' => 3,
'ajax' => array(
'url' => Yii::app()->createUrl('etelOsszerendeles/filterOsszetevo'),
'dataType' => 'json',
'quietMillis'=> 100,
'data' => 'js: function(text,page) {
return {
q: text,
page_limit: 10,
page: page,
};
}',
'results'=>'js:function(data,page) { var more = (page * 10) < data.total; return {results: data, more:more }; }',
),
),
));?>
My controller's action filter:
public function actionFilterOsszetevo()
{
$list = EtelOsszetevo::model()->findAll('nev like :osszetevo_neve',array(':osszetevo_neve'=>"%".$_GET['q']."%"));
$result = array();
foreach ($list as $item){
$result[] = array(
'id'=>$item->id,
'text'=>$item->nev,
);
}
echo CJSON::encode($result);
}
I use initSelection to load existing record for update in this way (I replaced some of your view code with ... to focus in main changes). Tested with Yii 1.1.14. Essentially, I use two different ajax calls:
View:
<?php
$this->widget('ext.select2.ESelect2', array(
'selector' => '#EtelOsszerendeles_osszetevo_id',
'options' => array(
...
...
'ajax' => array(
'url' => Yii::app()->createUrl('client/searchByQuery'),
...
...
'data' => 'js: function(text,page) {
return {
q: text,
...
};
}',
...
),
'initSelection'=>'js:function(element,callback) {
var id=$(element).val(); // read #selector value
if ( id !== "" ) {
$.ajax("'.Yii::app()->createUrl('client/searchById').'", {
data: { id: id },
dataType: "json"
}).done(function(data,textStatus, jqXHR) { callback(data[0]); });
}
}',
),
));
?>
Now in your controller you should receive parameters for ajax processing: query (q), as string, when inserting; id (id) as int when updating. Parameter names must be same as ajax data parameters (in this sample insert q; in update id) when read in $_GET. Code is not refactored/optimized:
Controller:
public function actionSearchByQuery(){
$data = Client::model()->searchByQuery( (string)$_GET['q'] );
$result = array();
foreach($data as $item):
$result[] = array(
'id' => $item->id,
'text' => $item->name,
);
endforeach;
header('Content-type: application/json');
echo CJSON::encode( $result );
Yii::app()->end();
}
public function actionSearchById(){
$data = Client::model()->findByPk( (int) $_GET['id'] );
$result = array();
foreach($data as $item):
$result[] = array(
'id' => $item->id,
'text' => $item->name,
);
endforeach;
header('Content-type: application/json');
echo CJSON::encode( $result );
Yii::app()->end();
}
Model - custom query and a little of order / security / clean :)
public function searchByQuery( $query='' ) {
$criteria = new CDbCriteria;
$criteria->select = 'id, ssn, full_name';
$criteria->condition = "ssn LIKE :ssn OR full_name LIKE :full_name";
$criteria->params = array (
':ssn' => '%'. $query .'%',
':full_name' => '%'. $query .'%',
);
$criteria->limit = 10;
return $this->findAll( $criteria );
}
EDIT:
It works out of box when update is preloaded with traditional HTTP Post (synchronous, for example with Yii generated forms). For async/Ajax updates, for example with JQuery:
Event / Trigger:
$('#button').on("click", function(e) {
...
... your update logic, ajax request, read values, etc
...
$('#select2_element').select2('val', id_to_load );
});
With this, initSelection will run again in async way with new id_to_load value, reloading record by id.
In your case and for your needs, initSelection could be complete different to avoid load record from db or you can use formatResult and formatSelection custom functions (are described in Load Remote Data sample source code). Reading documentation, I understand that initSelection's callback need JSON data with id and text elements to load properly or you could try to combine both concepts (this initSelection with your custom JS event/trigger call) (not tested):
'initSelection'=>'js:function(element,callback) {
// here your code to load and build your values,
// this is very basic sample
var id='myId';
var text='myValue';
data = {
"id": id,
"text": text
}
callback(data);
}',
Or directly on Trigger call:
$('#button').on("click", function(e) {
...
... ...
$("#select2_element").select2("data", {id: "myId", text: "MyVal"});
});
Hope that helps.
I tried doing that way, but couldn't do it
the solution I came up to get my record filled and selected was:
In case of the attribute having some data(in update mode or default value), I wrote some javascript that after document ready event, would fill the select with my data (just selected it ind pushed html in it), and made it selected, and then I rest( or update) the select to show my work.
I am trying to build a set of linked/chained multiselect boxes using MagicSuggest and a php query. So, first I build a MagicSuggest box with a function for when ms1 is changed:
$(document).ready(function() {
var ms1 = $('#ms1').magicSuggest({
data: 'datams1.php',
displayField: 'name' });
$(ms1).on('selectionchange', function(event, combo, selection){
run(selection);});
});
Then I build a new MagicSuggest box by running a php query that returns a json object:
function run(country) {
$.getJSON("query.php", { id: country[0].id}, callbackFuncWithData );
}
function callbackFuncWithData(region) {
var ms2 = $('#ms2').magicSuggest({
data: region,
displayField: 'name'
});
}
This works once I make an initial selection, but does not update if I change the selection. I have checked and within my "callbackFuncWithData" I am producing an updated "region" json object. So it might just be that I need to refresh/reload my #ms2 object.
My questions are:
Is there a way to force an refresh of the MagicSuggest data?
Is there a better/cleaner/more efficient way to use the results of one MagicSuggest box to query and return the data for a second, linked MagicSuggest box?
Thanks!
use setData() method to dynamically set the data when needed.
you can always use a library like angular to bind the component properties together.
This code makes 2 linked combos with the same data, but one of them shows the "name" field and the other one shows the "name1" filed.
function reflectSelection(ms1, ms2){
var val = parseInt(ms1.getValue());
var val1 = parseInt(ms2.getValue());
if(!isNaN(val)){
if(val != val1){
ms2.clear(true);
ms2.setSelection(ms1.getSelection());
}
}
else
{
ms2.clear(true);
}
}
var msName = $('#ms-onselectionchange').magicSuggest({
maxSelectionRenderer: function(){ return ''; },
useTabKey: true,
noSuggestionText: '',
strictSuggest: true,
maxSelection: 1,
allowFreeEntries: false,
placeholder : '',
data: [{'id':0, 'name':'Paris', 'name1':'Paris5'}, {'id':1, 'name':'New York', 'name1':'New York5'}],
});
var msName1 = $('#ms-onselectionchange1').magicSuggest({
maxSelectionRenderer: function(){ return ''; },
useTabKey: true,
noSuggestionText: '',
displayField: 'name1',
strictSuggest: true,
maxSelection: 1,
allowFreeEntries: false,
placeholder : '',
data: [{'id':0, 'name':'Paris', 'name1':'Paris5'}, {'id':1, 'name':'New York', 'name1':'New York5'}],
});
$(msName).on('selectionchange', function(e,m){
reflectSelection(msName, msName1);
});
$(msName1).on('selectionchange', function(e,m){
reflectSelection(msName1, msName);
});