I have written a Apex class which return the list of objects in a String to be add in the drop down list in the AURA cmp Now I want to change the API name to label in the JS controller itself so is there any to fetch the Label from the API name.
doInit: function(component, event, helper) {
var action = component.get("c.getAllObjects");
var inputIndustry = component.find("InputAccountIndustry");
var opts=[];
action.setCallback(this, function(a) {
opts.push({
class: "optionClass",
label: "--- None ---",
value: ""
});
for(var i=0;i< a.getReturnValue().length;i++){
console.log(a.getReturnValue()[i]);
var labelReference = $A.getLabel("$Label.c.---" + a.getReturnValue()[i]);
console.log('label is ' + labelReference);
opts.push({"class": "optionClass", label: a.getReturnValue()[i], value: a.getReturnValue()[i]});
}
inputIndustry.set("v.options", opts);
});
$A.enqueueAction(action);
},
Related
I have a listbox in view.
This Listbox use template
Listbox
<div id="UsersLoad" style="width: 50%">
#Html.EditorFor(i => i.Users, "UsersForEdit")
</div>
Template UserForEdit (Part of the code)
#model string[]
#{
if (this.Model != null && this.Model.Length > 0)
{
foreach(var item in this.Model)
{
listValues.Add(new SelectListItem { Selected = true, Value = item, Text = item });
}
}
else
{
listValues = new List<SelectListItem>();
}
}
<div class="field-#size #css">
<h3>#Html.LabelFor(model => model):</h3>
#Html.ListBoxFor(model => model, listValues, new { id = id })
</div>
In another view div "Users" is called.
function LoadUsersCheckBox() {
$("#UsersLoad").load('#Url.Action("LoadUsers", "User")' + '?idUser=' + idUser);
}
LoadUsers Controller
public JsonResult LoadUsers(int? idUser)
{
var users = Service.GetSystemUsers(idUser);
var model = users.Select(x => new
{
Value = x,
Description = x
});
return this.Json(model, JsonRequestBehavior.AllowGet);
}
The controller method returns what I want.
But instead of it select the items in the listbox it overwrites the listbox with only the text of found users.
How to mark the items in the listbox on the function LoadUsersCheckBox?
Sorry for my bad English
The jQuery load() method "loads data from the server and places the returned HTML into the matched element." Note the words "the returned HTML". See http://api.jquery.com/load/
To select existing items, you should try get() instead (http://api.jquery.com/jQuery.get/). In the success callback handler, you will need to parse the returned data to an array. Then use an iterator to go over the items in the listbox, and if they exist in the parsed array, mark them as selected. Something like:
$.get("action url", function(data) {
var users = $.parseJSON(data);
$("#UsersLoad option").each(function() {
var opt = $(this),
value = opt.attr("value");
opt.removeAttr("selected");
if (users.indexOf(value) > -1) {
opt.attr("selected", "selected");
}
});
});
this is jquery function-
now i am able to pass the city name and save it to database but how to change locality with change in city name. i am zero at jquery.Unable to understand this line $.getJSON(localityUrl, { ID: $(this).val() }, function (data) { plzzz suggest me some changes to be made--
<script type="text/javascript">
$(document).ready(function () {
var localityUrl = '#Url.Action("FetchLocalities")';
var localities = $('#SelectedLocality');
$('#SelectedCity').change(function () { localities.empty();
subLocalities.empty();
$.getJSON(localityUrl, { ID: $(this).val() }, function (data) {
if (!data) {
return;
}
localities.append($('<option></option>').val('').text('Please select'));
$.each(data, function (index, item) {
localities.append($('<option></option>').val(item.Value).text(item.Text));
// localities.append($('<option data-lat=' + item.Latitude + ' data-lng=' + item.Longitude + '></option>').text(item.Text));
});
});
})
and my city drop down is like this ---------
<div class="editor-label">
#Html.LabelFor(model => model.SelectedCity)
</div>
<div class="editor-field">
<select id="SelectedCity" name="SelectedCity">
#foreach (var thisCity in Model.CityList)
{
<option value="#thisCity.Name" data-lat="#thisCity.Latitude" data-long="#thisCity.Longitude" data-name="#thisCity.Name" >#thisCity.Name</option>
}
</select>
#Html.ValidationMessageFor(model => model.SelectedCity)
</div>
and my cities in the service layer are like this---
public List<City> FetchCities()
{
List<City> cities = new List<City>();
cities.Add(new City() { Id = 1, Name = "--Select Your City--", Latitude = 28.6139M, Longitude = 77.2090M });
cities.Add(new City() { Id = 2, Name = "Faridabaad", Latitude = 28.4211M, Longitude = 77.3078M });
return cities;
}
and my localities are like this---
public List<Locality> FetchLocalities()
{
List<Locality> localities = new List<Locality>();
localities.Add(new Locality() { Id = 1, CityName = "Faridabaad", Name = "East Faridabaad" });
localities.Add(new Locality() { Id = 2, CityName = "Faridabaad", Name = "West Faridabaad" });
return localities;
}
now my controller is something like this to fetch localities--
public JsonResult FetchLocalities(string name)
{
var data = _localityService.FetchLocalities()
//.Where(l => l.CityId == Id)
.Where(l => l.CityName == name)
.Select(l => new { Value = l.CityName, Text = l.Name });
return Json(data, JsonRequestBehavior.AllowGet);
}
localityUrl is the url your calling- in your case it would be var localityUrl = '#Url.Action("FetchLocalities", "yourControllerName")';
{ ID: $(this).val() } is the data your passing to the controller, in your case it needs to be { name: $(this).val() } because your method has parameter string name (not ID) and $(this).val() equates to the value of the selected option
and data in function (data) is the data your returning back from the controller method, in your case a collection of objects containing 2 properties, Value and Text
Instead of using $.getJSON() you can make an ajax call to your controller action and reload all the localities separately by passing the desired parameter.
I have a table and I want retrieve a item details of a element that i sesect:
var tableArtConNom=sap.ui.core.Core().byId("artSnzNomDetail").byId("tableArtConNom");
tableArtConNom.attachItemPress(this.handleRowPress);
tableArtConNom.setModel(new sap.ui.model.json.JSONModel(p_oDataModel));
tableArtConNom.destroyColumns();
tableArtConNom.removeAllColumns();
console.log(tableArtConNom.getColumns());
for(var i=0; i<tableArtConNom.getModel().getProperty("/cols").length; i++){
tableArtConNom.addColumn(new sap.m.Column("colonna"+i, { header: new sap.m.Label({ text: tableArtConNom.getModel().getProperty("/cols")[i] })}));
}
tableArtConNom.destroyItems();
tableArtConNom.removeAllItems();
tableArtConNom.bindAggregation("items", "/items", new sap.m.ColumnListItem({
cells: tableArtConNom.getModel().getProperty("/cols").map(function (colname) {
return new sap.m.Label({ text: "{" + colname + "}" });
}),
type:"Navigation"
}));
if(this.byId("idCodNomDog").getProperty("text")!=""){
var buttonAccept=this.byId("idButtonAccept");
buttonAccept.setProperty("visible", true);
}else{
var buttonAccept=this.byId("idButtonAccept");
buttonAccept.setProperty("visible", false);
}
tableArtConNom.setModel(new sap.ui.model.json.JSONModel(p_oDataModelFull), "fullDataModel");
},
To do it I capture the press event but I find only a number of item:
//IF CLICK ON ROW
handleRowPress : function(evt){
var selectedRowNum = evt.getSource().indexOfItem(evt.getParameter("listItem"));
console.log(selectedRowNum);
},
How can I print the other detailx (for example the content of a column?)
p.s. I can't parse the model of all my rows because in the table I filter the data and the index that i clicked not match by the position in the total model.
in your event handler, use :
var oItem = evt.getParameter("listItem").getBindingContext().getObject();
//NB: if using standard sap.ui.table.Table, use:
//var oItem = evt.getSource().getBindingContext().getObject();
console.log(oItem); //prints the JSON for your selected table row
I use bootstrap multi-select and I want to update options on flow with ajax
To populate on init my multiselect I do
<select name="model" class="multiselect" multiple="multiple">
<? foreach ($sel_models as $mod) { ?>
<option value="<?= $mod ?>" <?= ($mod == $params['model']) ? 'selected' : '' ?>><?= $mod ?></option>
<? } ?>
</select>
then on event I would like to update my option list with the following ajax
I was trying to use the rebuild method but won't fire the drop-down after creation
$.ajax({
type: 'post',
url: "helper/ajax_search.php",
data: {models: decodeURIComponent(brands)},
dataType: 'json',
success: function(data) {
$('select.multiselect').empty();
$('select.multiselect').append(
$('<option></option>')
.text('alle')
.val('alle')
);
$.each(data, function(index, html) {
$('select.multiselect').append(
$('<option></option>')
.text(html.name)
.val(html.name)
);
});
$('.multiselect').multiselect('rebuild')
},
error: function(error) {
console.log("Error:");
console.log(error);
}
});
With firebug I can see that the list is generated but on select won't show up
In the doc I can read :
.multiselect('setOptions', options)
Used to change configuration after initializing the multiselect. This may be useful in combination with .multiselect('rebuild').
Maybe you can't change your widget data by your initial way. In a correct way you should use setOptions method.
Else : With your way, maybe should you think about destroy your widget .multiselect('destroy') and create it again after.
Update after comment :
In the doc : ( you've linked )
Provides data for building the select's options the following way:
var data = [
{label: "ACNP", value: "ACNP"},
{label: "test", value: "test"}
];
$("#multiselect").multiselect('dataprovider', data);
So :
When you get data from your ajax call, you have to create an array of objects ( it's the options in the select you want to have ) with the format like
var data =
[
{label: 'option1Label', value: 'option1Value'},
{label: 'option2Label', value: 'option2Value'},
...
]
When your objects array is created, then you just have to call the method
$("#multiselect").multiselect('dataprovider', data);
Where data is your array of objects.
I hope I'm clear :/
As an alternative to multiselect('dataprovider', data) you can build the list with jquery append exactly the way you did in your question. The only change you need to make is to delay the rebuild until after the ajax request is complete.
var buildDrivers = $.getJSON('resources/orders/drivers.json', function(data) {
$.each(data, function(i, driver) {
$('#toolbar select[name="drivers"]').append('<option>'+driver+'</option>');
});
});
buildDrivers.complete(function() {
$('.multiselect').multiselect('rebuild');
});
see http://api.jquery.com/jquery.getjson/ for documentation
I've been added the functionality of updating options after filtering and getting them from the server side. This solution relays on the concept of injecting new options, destroying the select and initializing it again.
I took into account:
Considering the existing selected options, which must stay.
Removing duplicate options (might be as a conflict from which that already selected and the new that came from the server).
Keeping the options tray open after the update.
Reassign the previous text in the search text box & focusing it.
Just add the 'updateOptions' as a function after the 'refresh' function along with the two helper functions as follows:
updateOptions: function (options) {
var select = this.$select;
options += this.getSelectedOptionsString();
var selectedIds = select.val(),
btnGroup = select.next('.btn-group'),
searchInput = btnGroup.find('.multiselect-search'),
inputVal = searchInput.val();
options = this.removeOptionsDuplications(options);
if (!options) {
options = '<option disabled></option>';
}
// 1) Replacing the options with new & already selected options
select.html(options);
// 2) Destroyng the select
select.multiselect('destroy');
// 3) Reselecting the previously selected values
if (selectedIds) {
select.val(selectedIds);
}
// 4) Initialize the select again after destroying it
select.multiselect(this.options);
btnGroup = select.next('.btn-group');
searchInput = btnGroup.find('.multiselect-search');
// 5) Keep the tray options open
btnGroup.addClass('open');
// 6) Setting the search input again & focusing it
searchInput.val(inputVal);
searchInput.focus();
},
getSelectedOptionsString: function () { // Helper
var result = '',
select = this.$select,
options = select.find('option:selected');
if (options && options.length) {
$.each(options, function (index, value) {
if (value) {
result += value.outerHTML;
}
});
}
return result;
},
removeOptionsDuplications: function (options) { // Helper
var result = '',
ids = new Object();
if (options && options.length) {
options = $(options);
$.each(options, function (index, value) {
var option = $(value),
optionId = option.attr('value');
if (optionId) {
if (!ids[optionId]) {
result += option[0].outerHTML;
ids[optionId] = true;
}
}
});
}
return result;
},
Demo:
State:
"Option 1"
$('#select').multiselect('updateOptions', '<option value="2">Option 2</option>');
State:
"Option 2"
"Option 1"
I think this is an easier way to add options on the fly (using ajax or any other listener) to an existing Bootstrap MultiSelect.
Following is a simplified example to add options:
function addOptionToMultiSelect(multiselectSelector, value, selected) {
var data = [];
$(multiselectSelector + ' option').each(function(){
var value = $(this)[0].value;
var selected = $(this)[0].selected;
data.push({label: value, value: value, selected: selected});
});
// Add the new item
data.push({label: value, value: value, selected: selected});
$(multiselectSelector).multiselect('dataprovider', data);
}
For simplicity, I have assumed both the label and value are the same in an option. Note that the already selected options are taken care of by reading the selected attribute from the existing options. You can make it more sophisticated by tracking the disabled and other attributes.
Sample:
addOptionToMultiSelect('#multiselect-example', 'new-option', true);
The documentation provides an example:
aContainer = Ember.ContainerView.create({
childViews: ['aView', 'bView', 'cView'],
aView: Ember.View.create(),
bView: Ember.View.create(),
cView: Ember.View.create()
});
This is really neat, however if I want to write a function that adds views when called, how do I name each view that I create? for example:
aContainer = Ember.ContainerView.create({
childViews: [],
newView: function( input ){
var newView = BaseView.create({ field: input });
this.get('childViews').pushObject( newView );
}
});
this seem to push an anonymous view into the container. Any thoughts on how to name it?
For example, it'd be neat to have a snippet that says:
newView: function( input ){
var name = 'view_' + this.get('childViews').get('length') + 1
var newView = BaseView.create({ field: input, meta: name })
this.get('childViews').pushObject( newView );
}
Thank you.
I don't think there's a meta attribute to add named views. But you can always just assign them yourself.
newView: function( input ){
var name = 'view_' + this.get('childViews.length') + 1
var newView = BaseView.create({ field: input });
this.get('childViews').pushObject( newView );
this.set(name, newView);
}