Selecfield set options from array - javascript

Hi I have a json with array of values and I want to set this values as options to the selectfield. Not sure how to go ahead with this scenario.Any help is appreciated.
Below is my code for json and javascript function which returns the xtype selectfeild
var json= {
"metric": {
"areaInput": ["um", "mm", "cm", "m", "dm", "km"],
"areaResult": ["um", "mm", "cm", "m", "ha", "dm", "km"],
"volumeInput": ["mm", "cm", "m", "km"],
"volumeResult": ["ml", "tsp", "tbs", "l", "mm", "cm", "m", "km"],
"weight": ["g", "kg", "mg", "t"]
},
"imperial": {
"areaInput": ["in", "ft", "yd", "fur", "mi", "nmi"],
"areaResult": ["in", "ft", "yd", "mi", "nmi", "acre"],
"volumeInput": ["in", "ft", "yd", "mi"],
"volumeResult": ["in", "oz", "fl.oz", "pt", "qt", "gal", "tbs", "tsp", "cups", "ft", "yd", "mi"],
"weight": ["oz", "lb", "t", "oz.tr.", "grains"]
}
},
selectBoxUnit: function(eachInput){
var options = [];
for (h in json.metric) {
options.push({text: json.metric[h], value: h});
}
Ext.getCmp('myselect').add(options);
return {
xtype: 'selectfield',
usePicker : false,
itemId: eachInput.itemId+"selectfield",
name: eachInput.itemId,
id:'myselect',
flex: 1,
options: options,
listeners: {
change: function (field, value) {
field.setOptions([{
value: "newvalue",
text: "My new value"
}], true);
}
}
}
};

I'm quite new to Sencha Touch 2. I write this example for you. May be it will help you. You must set datastore to
selectfield. After this you can very easy add items to this
datastore and options will be created.
Ext.define('OptionModel', {
extend: 'Ext.data.Model',
config: {
fields: [
{name: 'text', type: 'string'},
{name: 'value', type: 'string'}
]
}
});
var optionsStore = Ext.create('Ext.data.Store', {
model: 'OptionModel'
});
Ext.application({
name: 'Test',
launch: function () {
Ext.Viewport.add({
xtype: 'panel',
fullscreen: true,
items: [
{
xtype: 'fieldset',
title: 'Select',
items: [
{
xtype: 'selectfield',
label: 'Choose item',
id: 'selectItemId',
store: optionsStore
}
]
},
{
xtype: 'button',
text: 'Add new item',
listeners: {
tap: function () {
var optionValueText = "Item " + optionsStore.getCount();
// here is the magic
optionsStore.add({
text: optionValueText,
value: 'somevalue'
});
// here we set new added item
// to be selected (active into select)
Ext.ComponentQuery.query('#selectItemId')[0].setValue(optionValueText);
}
}
}
]
});
}
});

Related

How to add new data items to an existing JavaScript object

I am trying to add new items to an existing JavaScript object as shown below. But both methods throw errors. I could create two separate objects by hard-coding with these values, but want to avoid it.
var defaultAmountTypeData = [
{ text: "Dollar", value: "D" },
{ text: "Percent", value: "P" },
{ text: "Sale", value: "S" },
];
var updatedAmountTypeData = [
{ text: "Dollar", value: "D" },
{ text: "Percent", value: "P" },
{ text: "Sale", value: "S" },
{ text: "New Amount", value: "NA" },
{ text: "New Percent", value: "NP" },
];
Tried the following:
Solution 1:
var updatedAmountTypeData = [
defaultAmountTypeData,
{ text: "New Amount", value: "NA" },
{ text: "New Percent", value: "NP" },
];
Solution 2:
var updatedAmountTypeData = getUpdatedAmountTypeData(){
var newobj = Object.assign(defaultAmountTypeData, {
text: "New Amount",
value: "NA",
});
newobj = Object.assign(newobj, { text: "New Percent", value: "NP" });
return newobj;
}
Use ellipsis to combine arrays.
var updatedAmountTypeData =
[
...defaultAmountTypeData,
{ text: "New Amount", value: "NA" },
{ text: "New Percent", value: "NP" }
];

Comparing two arrays - removing element from array based on object keys

I have two objects.
const arrayOne = [
{
label: "Categories",
to: "/categories",
id: "product_type",
},
{
label: "Colors",
to: "/colors",
id: "color",
},
{
label: "Materials",
to: "/materials",
id: "material",
},
{
label: "Sizes",
to: "/sizes",
id: "sizes",
},
{
label: "Designers",
to: "/designers",
id: "designer_slug",
},
{
label: "Stores",
to: "/stores",
id: "retailer_slug",
},
];
const arrayTwo = [
{
id: "gender",
label: "Gender",
lazy_loaded: false,
},
{
id: "product_type",
label: "Category",
lazy_loaded: false,
},
{
id: "quick_filters",
label: "Quick filters",
lazy_loaded: false,
},
{
id: "final_price",
label: "Price",
lazy_loaded: false,
},
{
id: "color",
label: "Color",
lazy_loaded: false,
},
{
id: "material",
label: "Material",
lazy_loaded: false,
},
{
id: "designer_slug",
label: "Brand",
lazy_loaded: true,
},
{
id: "retailer_slug",
label: "Store",
lazy_loaded: true,
},
];
As you can see they both have the key 'id'. If the IDs in arrayOne aren't in arrayTwo, I would like them to be removed from arrayOne (the whole object). So in this case, only the object with "sizes" should be removed from arrayOne. How would I go about doing this? Thanks in advance!
you could utilize filter:
const newArrayOne = arrayOne.filter(x => arrayTwo.find(y => y.id === x.id))
You could use a Set with id and filter the other array.
const
arrayOne = [{ label: "Categories", to: "/categories", id: "product_type" }, { label: "Colors", to: "/colors", id: "color" }, { label: "Materials", to: "/materials", id: "material" }, { label: "Sizes", to: "/sizes", id: "sizes" }, { label: "Designers", to: "/designers", id: "designer_slug" }, { label: "Stores", to: "/stores", id: "retailer_slug" }],
arrayTwo = [{ id: "gender", label: "Gender", lazy_loaded: false }, { id: "product_type", label: "Category", lazy_loaded: false }, { id: "quick_filters", label: "Quick filters", lazy_loaded: false }, { id: "final_price", label: "Price", lazy_loaded: false }, { id: "color", label: "Color", lazy_loaded: false }, { id: "material", label: "Material", lazy_loaded: false }, { id: "designer_slug", label: "Brand", lazy_loaded: true }, { id: "retailer_slug", label: "Store", lazy_loaded: true }],
two = new Set(arrayTwo.map(({ id }) => id)),
result = arrayOne.filter(({ id }) => two.has(id));
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Ag-Grid Tree like structure attach cellClass to NodeChildren cells based on validation

In my Jquery&JavaScript, Angular, all seperate applications i have included Ag-Grid with columnDefs like below :-
this.columnDefs = [
{
headerName: "Age",
field: "age",
cellRenderer: "agGroupCellRenderer"
},
{
headerName: "Name",
field: "name"
},
{
headerName: "Year",
field: "year"
},
{
headerName: "Country",
field: "country"
}
];
and my row Data is like below
this.rowData = [
{
age: "Group A",
participants: [
{
age: 1,
name: "Michael Phelps",
year: "2008",
country: "United States"
},
{
name: "A.2",
age: 2,
year: "2008",
country: "United States"
},
{
name: "A.3",
age: 50,
year: "2008",
country: "United States"
}
]}];
this.getNodeChildDetails = function getNodeChildDetails(rowItem) {
if (rowItem.participants) {
return {
group: true,
children: rowItem.participants,
};
} else {
return null;
}
Now i want to attach cellClass to children grid values based on validation, like:-
if(age< 23 || ''){
return['classNameThatiWantToAttach'];
}
How to do this ??
You can make changes in below plunker also for this: -
https://plnkr.co/edit/lmjtuqfId4FIsTI5luL8?p=preview
You can do it like this
edit the column definitions and add a cellClass function to it
{
headerName: "Year",
field: "year",
editable: true,
cellClass: this.cellClass
}
Then define the function and add the conditions you need and return a string with the value of the class
cellClass(params) {
if (params.value >= 2015)
return "redClass"
}
Don't forget to add the css styling for the classes.
Example
Please see the updated plunkr showing a cell in red color as per validation of the age:
https://plnkr.co/edit/QZd2MM1LflQaruxdCmym?p=preview
this.columnDefs = [
// ...
{
headerName: "Age",
field: "age",
cellClassRules: this.getCssClass()
}
// ...
];
getCssClass(): {[cssClassName: string]: (Function | string)} {
return {
'invalid-age': this.validateAge(),
};
}

ui-grid display cell as select tag

I have an example of ui-grid that one of the column represent sex type ('Gender':male , female..).
The json data that binding to the grid contain just the code type like (1, 2, 3...)
But I want to display the sex name like 'male' if the code is 1 and so on
And when the user choose from list new gender i want to display the new sex name
And update the sex code in the json data.
In fact, it was so far when I used basic HTML table (I add example in plnkr link)
any idea ?
// Code goes here and link for plunker :http://plnkr.co/edit/g6xYama3MidekeDqI3p8?p=preview
var app = angular.module('app', ['ngAnimate', 'ui.grid', 'ui.grid.edit','ui.grid.cellNav']);
app.controller('MainCtrl', ['$scope', '$http',
function($scope, $http) {
$scope.genderTypes = [{
ID: 1,
type: 'male'
}, {
ID: 2,
type: 'female'
}, {
ID: 3,
type: 'both'
}, {
ID: 4,
type: 'none'
}, ];
$scope.gridOptions = {
enableSorting: true,
enableFiltering: true,
enableCellEditOnFocus: true,
columnDefs: [{
field: 'name',
sort: {
direction: 'desc',
priority: 1
}
}, {
field: 'gender',
editType: 'dropdown',
enableCellEdit: true,
editableCellTemplate: 'ui-grid/dropdownEditor',
editDropdownOptionsArray: $scope.genderTypes,
editDropdownIdLabel: 'ID',
editDropdownValueLabel: 'type'
}, {
field: 'company',
enableSorting: false
}],
onRegisterApi: function(gridApi) {
grid = gridApi.grid;
}
};
$scope.gridOptions.data = [ { "name": "Ethel Price", "gender": "1", "company": "Enersol" }, { "name": "Claudine Neal", "gender": "2", "company": "Sealoud" }, { "name": "Beryl Rice", "gender": "3", "company": "Velity" }, { "name": "Wilder Gonzales", "gender": "4", "company": "Geekko" }, { "name": "Georgina Schultz", "gender": "1", "company": "Suretech" }]
}
]);
You need to apply a cell filter. I've forked your plunkr with a solution.
Filter:
app.filter('mapGender', function() {
var genderHash = {
1: 'male',
2: 'female',
3: 'both',
4: 'none'
};
return function(input) {
if (!input){
return '';
} else {
return genderHash[input];
}
};
});
Column Def:
{
field: 'gender',
editType: 'dropdown',
cellFilter: 'mapGender',
enableCellEdit: true,
editableCellTemplate: 'ui-grid/dropdownEditor',
editDropdownOptionsArray: $scope.genderTypes,
editDropdownIdLabel: 'ID',
editDropdownValueLabel: 'type'
}
Plunker: http://plnkr.co/edit/hnaMJjBGaQgMGcgt3Hc2?p=preview
References:
Custom UI-Grid Filters: http://ui-grid.info/docs/#/tutorial/306_custom_filters
Angular Filter: https://docs.angularjs.org/api/ng/filter/filter

Extjs5 : ComboBox not showing the selected value

I created a comboBox and when I select a value, no value will be displayed.
Ext.create("Ext.form.field.ComboBox", {
name: el.name,
fieldLabel: el.labelId,
hidden: !(el.visible),
displayField:"value",
valueField:"value",
flex: 1,
store:Ext.create("Ext.data.Store",{
fields: ['key', 'value'],
data: [
{ key: "10",value: "etap 0"},
{ key: "200",value: "etape 1"},
{ key: "300", value: "etape 3"}
]
}),
regex: el.parameterType.regex,
regexText: el.regExErrMsg,
allowBlank: !el.mandatory,
blankText: el.requiredErrMsg
})
EDIT
Here is exactly the method that return combo:
drawField: function (el) {
var me = this;
var uiField = Ext.create(me.componentType, {
name: el.name,
fieldLabel: el.labelId,
hidden: !(el.visible),
flex: 1,
regex: el.parameterType.regex,
regexText: el.regExErrMsg,
allowBlank: !el.mandatory,
blankText: el.requiredErrMsg
});
if (el.parameterType.isCombo) {
uiField.displayField = 'value';
uiField.valueField = 'key';
uiField.editable = false;
uiField.store = Ext.create('Ext.data.Store', {
fields: ['key', 'value'],
data: el.parameterType.values
});
}
return uiField;
}
and el parameter is a JavaScript object like that:
{
name: "",
labelId: "Champ :",
parameterType: {
regEx: "^.*$",
errID: "115",
isCombo: true,
values:[
{key: "10", value: "etap 0"},
{key: "200",value: "etape 1"},
{key: "300",value: "etape 3"},
],
selectedValue: "etap 0"
},
mandatory: false,
visible: true,
defaultValue: "",
elementType: "LIST_BOX",
regExErrMsg: "Valeur invalide.",
requiredErrMsg: ""
}
and me.componentType at runtime is Ext.form.field.ComboBox
This fiddle works fine for me, I removed the references to el as it shown undefined for me and also changed Ext.data.store to Ext.data.Store
https://fiddle.sencha.com/#fiddle/jj6
Ext.application({
name: 'Fiddle',
launch: function() {
Ext.create("Ext.form.field.ComboBox", {
renderTo: Ext.getBody(),
displayField: "value",
valueField: "value",
flex: 1,
store: Ext.create("Ext.data.Store", {
fields: ['key', 'value'],
data: [{
key: "10",
value: "etap 0"
}, {
key: "200",
value: "etape 1"
}, {
key: "300",
value: "etape 3"
}]
})
});
}
});
valueField:"value" is wrong, you should specify valueField:"key" in order for ComboBox to work properly

Categories