I'm a hobbyist developer. I'm using basic Select2 ajax in a new/edit Rails form, and I can't figure out how to re-populate it in the edit form. song_creditor_1 is a string, but it's entered as an id of Fan model.
form:
<%= f.input :song_creditor_1, label: 'Song Creditor 1', as: :select, input_html: { id: "song_creditor_1", include_hidden: false } %>
script
function templateDropDownFormat (item) {
return item.text;
}
function templateSelectionFormat (item) {
return item.text;
}
$("#song_creditor_1").select2({
placeholder: "Search",
ajax: {
url: "/songs",
dataType: 'json',
delay: 250,
data: function (params) {
return {
q: params.term, // search term
page: params.page
};
},
processResults: function (data, params) {
// parse the results into the format expected by Select2
// since we are using custom formatting functions we do not need to
// alter the remote JSON data, except to indicate that infinite
// scrolling can be used
params.page = params.page || 1;
return {
results: $.map(data, function(cnut) {
return {
text: cnut.name + ", " + cnut.city + ", " + cnut.country + " (" + cnut.account_type + ")",
id: cnut.id,
};
}),
pagination: {
more: (params.page * 30) < data.total_count
}
};
},
cache: true
},
escapeMarkup: function (markup) { return markup; }, // let our custom formatter work
minimumInputLength: 1,
templateResult: templateDropDownFormat, // omitted for brevity, see the source of this page
templateSelection: templateSelectionFormat// omitted for brevity, see the source of this page
});
Well, I'm just a hobbyist, and this is my first website, so this answer isn't pretty but it's how I resolved it. The issue was having to re-populate the data in the field if there was an error on the form, so I just pulled that particular attribute out during the 'create' and called it #creditor1.
var $select1 = $('#song_creditor_1');
function templateDropDownFormat (item) {
return item.text;
}
function templateSelectionFormat (item) {
return item.text;
}
$select1.select2({
ajax: {
url: "/songs",
dataType: 'json',
delay: 250,
data: function (params) {
return {
q: params.term, // search term
page: params.page
};
},
processResults: function (data, params) {
// parse the results into the format expected by Select2
// since we are using custom formatting functions we do not need to
// alter the remote JSON data, except to indicate that infinite
// scrolling can be used
params.page = params.page || 1;
return {
results: $.map(data, function(cnut) {
return {
text: cnut.name + ", " + cnut.city + ", " + cnut.country + " (" + cnut.account_type + ")",
id: cnut.id,
};
}),
pagination: {
more: (params.page * 30) < data.total_count
}
};
},
cache: true
},
escapeMarkup: function (markup) { return markup; }, // let our custom formatter work
minimumInputLength: 1,
templateResult: templateDropDownFormat, // omitted for brevity, see the source of this page
templateSelection: templateSelectionFormat// omitted for brevity, see the source of this page
});
<% if params[:action] === "edit" && #creditor1_real || params[:action] === "update" && #creditor1_real %>
var $option1 = $('<option selected><%= #creditor1_real.name %>, <%= #creditor1_real.city %>, <%= #creditor1_real.country %></option>').val("<%= #creditor1_real.id %>");
$select1.append($option1).trigger('change');
<% elsif params[:action] === "create" && #creditor1 || params[:action] === "new" && #creditor1 %>
var $option1 = $('<option selected><%= #creditor1.name %>, <%= #creditor1.city %>, <%= #creditor1.country %></option>').val("<%= #creditor1.id %>");
$select1.append($option1).trigger('change');
<% else %>
var $option1 = $('<option selected>Search</option>');
$select1.append($option1).trigger('change');
<% end %>
for me, i found solution to just find and plucking model in select options, while keeping the ajax source on js side
<%= f.select :song_creditor_1, Song.where(song_id: song.id).pluck(:song_name, :id), {}, class: 'your-select-2-class' %>
you can select all from your model, but in my case it slowing page load
Related
The scenario is, I need to set the value of the dropdown (ng-select2) when a user presses on edit button present on the page. I am using ajax to fetch the options. The code is in angular.
I took reference from : https://github.com/tealpartners/ng-select2
<div class="form-div">
<label for="uploader">Select Uploader<span class="asterick-red">*</span>
</label>
<ng-select2 formControlName="uploader" id="uploader" [options]="select2Options" width="270">
</ng-select2>
</div>
<div class="form-div">
<label for="uploader">Select Approver<span class="asterick-red">*</span>
</label>
<ng-select2 formControlName="approver" [id]="uploader" [options]="select2Options" width="270">
</ng-select2>
</div>
</div>
setSelect2Options() {
this.select2Options = {
triggerChange: true,
allowClear: true,
placeholder : 'Select User* ',
minimumInputLength: 3,
ajax: {
url: '/api/reward/uploader/approver/search/user?limit=15',
headers: {
'X-XSRF-TOKEN': sessionStorage.getItem("auth"),
'content-type': 'application/json'
},
dataType: 'json',
type: "GET",
quietMillis: 50,
data: function (term, page) {
return {
q: term.term, // search term
_: term._type
};
},
processResults: function (data) {
return {
results: $.map(data.results, function (item) {
return {
id: item.id,
text: item.name + " - " + item.email
}
})
};
}
},
//[placeholder]="'Select User* '"
}
}
The above codes are well and good. But now on a button click i need to set a value inn the select box.
this.vcDataService.getUploaderAproverDetails(id).subscribe((res: any) => {
this.uploaderApproverForm.controls['approver'].setValue(res.approverDetails.uploaderUserId);
this.uploaderApproverForm.controls['uploader'].setValue(res.uploaderDetails.approverUserId);
console.log("134", res)//uploaderUserId
//this.select2Options.ajax.processResults.push({id: 103, text: "aa"})
this.select2Options.placeholder="aa";
//this.displayUploader = "aaa";
// $('#uploader').val('ENABLED_FROM_JS');
// $('#uploader').trigger('change');
// this.select2Options.templateSelection = {
// selected: true,
// id: res.approverDetails.approverUserId,
// text: res.approverDetails.approverName,
// title: res.approverDetails.approverName
// }
// this.select2Options.initSelection = {
// callback: {
// data: {"id":103, "text":'ENABLED_FROM_JS'}
// }
// }
console.log(this.select2Options);
this.updateApproverUploader = true;
this.uploaderApproverId = res.uploaderApproverId;
this.cd.detectChanges();
},
err => {
Swal.fire('Oops...', err.error.err, 'error');
})
I tried few things but didn't got the workaround.
After going through the documentation I found a solution for it. I used the data attribute of the ng-select2 and assigned it to a Select2OptionData type variable.
import { Select2OptionData} from 'ng-select2';
patch_panel_array: Select2OptionData[];
Then I added the required data which I needed to show in the field as displayed below:
res.panelApprovers.map(item => {
this.patch_panel_array.push({
id: item.panelApproverUserId,
text: item.panelApproverUserName + " - " + item.panelApproverUserEmail
})
approverIds.push(String(item.panelApproverUserId));
});
this.formData.controls['panelApprover'].setValue(approverIds);
And here is my select 2 field:
<ng-select2 formControlName="panelApprover" [data]="patch_panel_array" [options]="select2OptionsPanel" width="100%" style="width: 100%;">
</ng-select2>
I need to send a parameter to Html.Kendo().Dialog():
var diff = Num1 = Num2;
var msg = "The amiunt of " + diff + " will be subtracted"
#(Html.Kendo().Dialog()
.Title("Update")
.Content("<p>" + msg + <p>")
However, that construct does not allow this, saying that "msg" does not exist in the current content
How can I do that?
Updated version:
if ((Math.abs(newAmount) < Math.abs(Amount)) && newAmount != 0) {
$("#dialog").kendoDialog({
width: "400px",
title: "Split Ticket Confirmation",
closable: true,
modal: true,
content: "<div style='text-align: center'>" + msg + "</div>",
actions: [
{
text: 'OK',
action: function (e) {
$('.modal-content').html('');
$('#modal-container').modal('hide');
SaveData();
},
primary: true
},
{
text: "CANCEL",
action: function (e) {
$('.modal-content').html('');
$('#modal-container').modal('hide');
return false;
},
primary: true
}
]
}).data("kendoDialog").open();
}
else {
SaveData();
}
Using Razor HTML C# syntax, you can achieve it without errors by doing this:
#{
var msg = "The amiunt of " + diff + " will be subtracted";
}
Then just passing it regularly to the Content as you already did.
If you are using JavaScript and really want to use that dialog inside script tags then you can do this:
var dialog = $('#dialog'), undo = $("#undo");
undo.click(function () {
dialog.data("kendoDialog").open();
undo.fadeOut();
});
function onClose() {
undo.fadeIn();
}
var diff = Num1 = Num2;
var msg = "The amiunt of " + diff + " will be subtracted";
dialog.kendoDialog({
width: "400px",
title: "Update",
closable: false,
modal: false,
content: "<p>" + msg + "<p>",
actions: [
{
text: "OK",
action: function(e){
// e.sender is a reference to the dialog widget object
// OK action was clicked
// Returning false will prevent the closing of the dialog
return false;
},
primary: true
},
{ text: 'Action 2' },
{ text: 'Action 3', primary: true }
],
close: onClose
});
To add another action per request, to the Html.Kendo.Dialog() construct you can do the following:
#Html.Kendo.Dialog()
.Actions(actions =>
{
actions.Add().Text("Ok").Action("onOkClick").Primary(true);
})
And inside your your script tag you create the JS method:
function onOkClick(e)
{
//Do something
}
What I am doing is writing a partial into the page on the event that opens the dialog:
function OpenDialog() {
$.ajax({
url: '#Url.Action("ItemSearch", "Invoice")',
data: {
PartNumber: dataItem.Id,
AltPartNumber: 1,
Description: 1,
Application: 1
},
success: function (result) {
$("#SearchDialogContainer").html(result);
},
error: function (result) {
alert("An error occurred.");
}
});
}
<div id="SearchDialogContainer"></div>
And in the partial:
#model ParameterModel
#(Html.Kendo().Dialog()
.Name("SearchDialog")
.Title("Choose An Item To Add")
.Content("<div class='k-textbox k-space-right search-wrapper'><input id='employees-search' type='text' placeholder='Search employees' value='#Model.Property'/></div>")
.Width(400)
.Modal(true)
.Visible(false)
.Actions(actions =>
{
actions.Add().Text("Add Item").Primary(true);
actions.Add().Text("Cancel");
})
)
<script>
$(document).ready(function () {
$('#SearchDialog').data("kendoDialog").open();
});
</script>
I'm trying to retrieve suppliers with select2 and ajax.
So this is my js code,
$(document).ready(function(){
$('.supplier_suggestion').select2({
placeholder: 'Search for supplier',
ajax: {
type: 'GET',
url: '/search_supplier',
delay: 250,
data: function(params){
var query = {
q: params.term
}
return query;
},
dataType: 'json',
processResults: function (data) {
return {
results: $.map(data, function (item) {
return {
text: item.text,
id: item.id
}
})
};
}
}
});});
I got this in my haml (which called the js file above)
%b.tosca XXX
.input-field
= f.text_field :supplier_name, class: "supplier_suggestion browser-default"
= error_for #ro_nonreg, :supplier_name
and this ini search_controller.rb
def search_supplier
search = params[:q]
search_pattern = '%' + search.downcase + '%'
result_raw = Supplier.where('lower(supplier_name) LIKE ? OR lower(shadow_id) LIKE ?', search_pattern, search_pattern)
result = []
result_raw.each do |data|
data_hash = {}
data_hash[:id] = data.shadow_id
data_hash[:text] = data.supplier_name
result << data_hash
end
render_secure_json supplier: result
end
what am i missing here?
Can't seem to figure out what the problem is here. This worked perfectly fine when using 3.5, but does not work with 4.0.
I am using select2.full.js as well which supports using input in this manner.
html:
<input id="vcreate-filter" type="text" name="settings[filter]" class="form-control" style="width:100%;"/>
js:
$("#vcreate-filter").select2({
placeholder: "Select or enter application...",
allowClear: true,
multiple: false,
ajax: {
dataType: 'json',
delay: 1000,
type: 'post',
url: '/process/get_application_list.php',
data: function (term, page) {
return {
term: term, // search term
page_limit: 25, // page size
page: page // page number
};
},
results: function (data, page) {
var more = (page * 25) < data.total; // whether or not there are more results available
return {
results: data.results,
more: more
};
}
},
createSearchChoice:function(term, data) {
if ($(data).filter(function() {
return this.text.localeCompare(term)===0; }).length===0) {
return {id:term, text:term};
}
}
}).on('change', function() {
$(this).valid();
});
get_application_list.php:
.......
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);
// make sure there are some results else a null query will be returned
if( count($results) > 0 )
{
foreach( $results as $row )
{
$ajax_result['results'][] = array(
'id' => htmlspecialchars($row['event_target'], ENT_QUOTES, 'UTF-8'),
'text' => htmlspecialchars($row['event_target'], ENT_QUOTES, 'UTF-8')
);
}
}
else
{
// 0 results send a message back to say so.
$ajax_result['results'][] = array(
'id' => 0,
'text' => 'No results found...'
);
}
// return result array to ajax
echo json_encode($ajax_result);
html: use select element instead of input.
<select id="vcreate-filter" type="text" name="settings[filter]" class="form-control" style="width:100%;"> </select>`
js: use processResults instead of 'results' as callback property.
processResults: function (data, page) {
var more = (page * 25) < data.total; // whether or not there are more results available
return {
results: data.results,
more: more
};
}
assuming the json is in the correct format [{"id": "1", "text": "One"}, {"id": "2", "text": "Two"}]
Breaking changes seems to be documented here.
I'm trying to make select2 working with my ajax loaded json data with nested attributes.
I wanna get something like this http://ivaynberg.github.io/select2/#multi.
eaxmple json:
[{
id: 1,
name: "GroupName",
users: [{id: 1, name: 'UserName'}, {id: 2, name: 'SecondUser}]
}]
On the site they use <optgroup label="GroupName"><option value="1">UserName</opyion></optgroup> and getting the right result.
In my case it displays nesting properly, but I can select only GroupName, but I need to select nested userName and make GrouoName unselectable, only gor informational purposes.
code:
$('#user_tokens').select2({
placeholder: "Search for a user",
minimumInputLength: 0,
tags: true,
multiple: true,
ajax: {
url: "messages/users_data.json",
dataType: 'json',
quietMillis: 100,
data: function(search, page) {
return {
q: search,
per: 3,
page: page
};
},
results: function(data, page) {
return {
results: data,
};
}
},
formatResult: formatResult,
formatSelection: formatSelection,
dropdownCssClass: "bigdrop"
});
formatResult:
var formatUserResult = function(data) {
var optgroup = "";
var users = "";
if (data.name !== undefined) {
data.users.forEach(function(e) {
users += "<li class='select2-results-dept-1 select2-result select2-result- selectable'>" +
"<div class='select2-result-label'>" +
"<span class='select2-match'></span>"+
e.firstname +
"</div>" +
"</li>";
});
optgroup += "<div class='select2-result-label'>" +
"<span class='select2-match'></span>" +
data.name + "</div>" +
'<ul class="select2-result-sub">' + users + '</ul>';
}
return optgroup;
}
The problem is that optgroup must have class: 'select2-result-unselectable'
Dunno what to do with it.