ExtJS -- dynamically generate checkboxes - extjs

I have a checkbox group which will have a dynamic number of checkboxes. The backend returns data containing the label and the input value. I loop these records and generate a checkbox object for each one. But when I pass the generated array into the items array, nothing happens.
Here are snippets of my checkbox group class.
Ext.define("MyApp.view.form.field.CheckboxGroup",{
extend:"Ext.form.CheckBoxGroup",
...
...
initComponent:function(){
this.items = getCheckboxes();
...
this.callParent(arguments);
},
getCheckboxes:function(){
Ext.Ajax.request({
url:"blah/getcheckboxes",
scope:this,
success:function(resp_){
var resp = Ext.JSON.decode(resp_.responseText);
var checkboxesArr = [];
if(resp.data){
for(var i=0; i<resp.data.length; i++){
checkboxesArr.push({boxLabel:resp.data[i].label, inputValue:resp.data[i].id, ....});
}
}
return checkboxesArr;
});
/*return checkboxesArr = [
{boxLabel: 'Yes', name: this.name, inputValue: 'Y'},
{boxLabel: 'No', name: this.name, inputValue: 'N'}
];*/
}
If I uncomment the static checkboxesArr with the 2 checkboxes and return that instead it works, but it doesnt work with the checkboxesArr generated with the backend response.
Thanks

The ajax call is asynchronous so you can add the items instead:
getCheckboxes: function () {
Ext.Ajax.request({
url: "data1.json",
scope: this,
success: function (resp_) {
var resp = Ext.JSON.decode(resp_.responseText);
var checkboxesArr = [];
if (resp.data) {
for (var i = 0; i < resp.data.length; i++) {
checkboxesArr.push({
boxLabel: resp.data[i].label,
inputValue: resp.data[i].id
});
}
}
this.add(checkboxesArr);
}
});
}
Working example: https://fiddle.sencha.com/#view/editor&fiddle/1lgc

Related

Populate Kendo Grid with Angular model list

I have an Angular app that retrieves my data from the server and would like to use the results to populate a kendo grid. I have tried to create a kendo.data.DataSource but can not get the grid to populate. Below is what I am trying.
$scope.surchargeGridOptions = {
dataSource: {
pageSize: 15,
autoSync: true,
autoBind: false,
data: $scope.model.dataSource,
}
$scope.getWaivers = function () {
waiverService.getCustomers($scope.model.customer.CustomerID).then(function (result) {
$scope.model.waivers = result.data;
$scope.model.dataSource = new kendo.data.DataSource({
data: $scope.model.waivers,
});
$scope.model.dataSource.read();
});
};
Is it possible to do this and how should I go about it?
The data source object in your options has a data property that only requires a reference to a plain array, not an entire kendo data source.
You should use k-data-source to reference your data...
<kendo-grid k-data-source="myData"></kendo-grid>
... and you don't strictly need a kendo data source to get it working...
$scope.myData = [
{ name: 'a', number: 1 },
{ name: 'b', number: 1 },
{ name: 'c', number: 1 },
{ name: 'd', number: 1 }
];
.. If you have dynamic data then a kendo observable array would be best practice.
Here is a code pen example.
Front Html Page having Grid option
<div kendo-grid="ListGrid" options="ListOptions" k-rebind="ListOptions" class="k-grid-content-border"></div>
function GridColumn() {
return [{
field: 'name',
template: "<a ng-click='ToList(this.dataItem)' class='cursor-pointer'>{{this.dataItem.name}}</a>",
title: "",
footerTemplate: "Total",
width: 200,
locked: true,
}]}
$scope.ToGeo = function (item) {
$scope.dataLoded = false;
GetResults(function (res) {
$scope.ListOptions.dataSource = new kendo.data.DataSource({
data: res,
});
$scope.ListOptions.columns = GridColumn();
$scope.ListGrid.refresh();
$scope.dataLoded = true;
})
}
where GetResults is for API call and fetching data

Need solution for Multi Select in Extjs tree

Am complete stranger to Extjs. I have a requirement to allow multi select in the Extjs tree. Below piece of code is doing single select. i need to change the code to make it multi select with semi-colon between selected ids. Can anyone please change the code as per the requirement. Also if you could tell me to which field or variable the selected value of the tree is written into. Thanks in advance
Ext.onReady(function() {
Ext.QuickTips.init();
var str='';
var switch_flag = '';
var approvals = '';
var active_mode = '';
var json = null;
Ext.Ajax.request({
url: 'Dmscategorytree/ajax/Message',
method: 'POST',
params:{
lifecycle_id: str,
switch_flag: switch_flag,
approvals: approvals,
active_mode: active_mode
},
success: function(response, options) {
var path='';
var id='';
var text='';
json=response.responseText;
alert(json);
json = json.replace(/"/g,'\"');
json=Ext.util.JSON.decode(json);
var flag=true;
var myloader = new Ext.tree.TreeLoader();
myloader.load = function(node, cb,scope) {
if(this.clearOnLoad){
while(node.firstChild){
node.removeChild(node.firstChild);
}
}
if(this.doPreload(node)){
this.runCallback(cb, scope || node, [node]);
}
cb();
}
var tree = new Ext.tree.TreePanel({
animate:true,
autoScroll:true,
//loader: new Tree.TreeLoader({dataUrl:'get-nodes.php'}),
containerScroll: true,
border: false,
loader:myloader,
rootVisible: false,
listeners:{
checkchange:function(node){
if(flag){
toggleCheck(tree.root,false,node.id);
path=node.attributes.value;
id=node.attributes.ID;
text=node.attributes.text;
path=path.replace(/\^/g,'/');
}
}
}
});
function SelectToParent()
{
try
{
parent.window.opener.callParent(path,id);
parent.window.opener.focus();
parent.window.close();
}
catch(e){
alert('got exception');
window.close();
}
}
function toggleCheck(node,isCheck,nodeId)
{
flag=false;
if(node)
{
var args=[isCheck];
node.cascade(function(){
c=args[0];
if(nodeId!=this.id){
this.ui.toggleCheck(c);
this.attributes.checked=c;
}
},null,args);
}
flag=true;
return true;
}
var root = new Ext.tree.AsyncTreeNode({
text: 'Ext JS',
draggable:false, // disable root node dragging
id:'src',
children: json
});
tree.setRootNode(root);
var topbar = new Ext.Toolbar({
region : 'north',
height:30,
margins: '0 0 0 5',
items:[
{
xtype: 'box',
id: 'title',
autoEl: {
html: '#label.chooseCat#'
}
,width:525
},
{
text: '#label.Done#',
id: 'doneBtn',
tooltip: 'Done',
handler: SelectToParent
}
]
});
topbar.render('tree');
tree.render('tree');
tree.getRootNode().expand();
}
});
});
Please refer the following links,
pass two id s in extjs 4 tree multiSelect and pass one id in single click
Multiselect Tree & Drag and Drop
Drag and Drop between Grid and “multiselect” control in EXTJS
Demo

Rally App SDK getting object ID of feature

var showAssignedProgram = 1;
var value = null;
var showIterationCombo = 0;
var iterationComboValue = null;
var lumenize = window.parent.Rally.data.lookback.Lumenize;
var iterationComboField = null;
var iterationRecord = myMask = null;
var setOfStories = setOfFeatures = null;
Ext.define('CustomApp', {
extend: 'Rally.app.App',
componentCls: 'app',
launch: function() {
//Write app code here
Ext.state.Manager.setProvider(
new Ext.state.CookieProvider({ expires: new Date(new Date().getTime()+(10006060247)) })
);
app = this;
var that = this;
console.log("launch");
// get the project id.
this.project = this.getContext().getProject().ObjectID;
// get the release (if on a page scoped to the release)
var tbName = getReleaseTimeBox(this);
var configs = [];
configs.push({ model : "Release",
fetch : ['Name', 'ObjectID', 'Project', 'ReleaseStartDate', 'ReleaseDate' ],
filters:[]
});
configs.push({ model : "Iteration",
fetch : ['Name', 'ObjectID', 'Project', 'StartDate', 'EndDate' ],
filters:[]
});
async.map( configs, this.wsapiQuery, function(err,results) {
that.releases = results[0];
that.iterations = results[1];
if (showAssignedProgram)
that.createAssignedProgramCombo();
that.createIterationCombo(that.iterations);
});
},
wsapiQuery : function( config , callback ) {
Ext.create('Rally.data.WsapiDataStore', {
autoLoad : true,
limit : "Infinity",
model : config.model,
fetch : config.fetch,
filters : config.filters,
listeners : {
scope : this,
load : function(store, data) {
callback(null,data);
}
}
});
},
createAssignedProgramCombo : function() {
// assigned Program (if set to true)
this.assignedProgramCombo = Ext.create("Rally.ui.combobox.FieldValueComboBox", {
model : "PortfolioItem/Feature",
field : "AssignedProgram",
stateful : true,
stateId : "assignedProgramCombo",
noData: false,
listeners:{
scope: this,
change: function(field,eOpts){
if(value!="" && value!=null)
{
this.afterCollapse(fieldValue,value);
}
}
}
});
this.add(this.assignedProgramCombo);
},
createIterationCombo: function(iterationRecords){
//console.log("Iteration records ",iterationRecords);
iterationRecord = iterationRecords;
var iterations = _.map(iterationRecords, function(rec){return {name: rec.get("Name"), objectid: rec.get("ObjectID"), startDate: new Date(Date.parse(rec.get("StartDate")))};});
console.log('iterations', iterations);
iterations = _.uniq(iterations, function(r){return r.name;});
iterations = _.sortBy(iterations, function(rec){return rec.StartDate;}).reverse();
var iterationStore = Ext.create('Ext.data.Store', {
fields: ['name','objectid'], data : iterations
});
var cb = Ext.create('Ext.form.ComboBox',{
fieldLabel: 'Iterations',
store: iterationStore,
queryMode: 'local',
displayField: 'name',
valueField: 'name',
listeners:{
scope: this,
change: function(field, eOpts){
console.log('field ', field, ' eOpts ',eOpts);
iterationComboValue = eOpts;
iterationComboField = field;
},
collapse: function(field, eOpts){
this.afterCollapse(field,eOpts);
}
}
});
this.add(cb);
},
afterCollapse: function(field,eOpts){
var r = [];
_.each(field.getValue().split(","), function(rn){
var matching_iterations = _.filter(iterationRecord, function(r){return rn == r.get("Name");});
var uniq_iterations = _.uniq(matching_iterations, function(r){return r.get("Name");});
_.each(uniq_iterations,function(iteration){r.push(iteration);});
});
if(r.length>0){
myMask = new Ext.LoadMask(Ext.getBody(), {msg:"Please wait..."});
myMask.show();
this.selectedIterations = r;
this.queryFeatures(r);
}
},
queryFeatures: function(iterations){
var that = this;
var filter = null;
if (showAssignedProgram && this.assignedProgramCombo.getValue() != null && this.assignedProgramCombo.getValue() != "") {
console.log("assingedValue",this.assignedProgramCombo.getValue());
filter = Ext.create('Rally.data.QueryFilter', {
property: 'AssignedProgram',
operator: '=',
value: this.assignedProgramCombo.getValue()
});
}
else{
_.each(iterations, function(iteration, i){
var f = Ext.create('Rally.data.QueryFilter', {
property: 'Iteration.Name',
operator: '=',
value: iteration.get("Name")
});
filter = i === 0 ? f : filter.or(f);
});
}
console.log("filter",filter.toString());
var configs = [];
configs.push({
model: 'PortfolioItem/Feature',
fetch: ['ObjectID','FormattedID','UserStories' ],
filters: [filter],
listeners: {
load: function(store, features) {
setOfFeatures = features;
console.log("# features",features.length,features);
that.StartDate = that.startDate(iterations);
that.start = _.min(_.pluck(iterations,function(r) { return r.get("StartDate");}));
isoStart = new lumenize.Time(that.start).getISOStringInTZ("America/Chicago");
console.log("isoStart1",isoStart);
that.end = _.max(_.pluck(iterations,function(r) { return r.get("EndDate");}));
that.iterations = iterations;
console.log('End date ',that.end);
// that.getStorySnapshotsForFeatures( features, iterations);
}
}
});
configs.push({
model: 'HierarchicalRequirement',
limit: 'Infinity',
fetch: ['Name','Iteration','ObjectID','Feature'],
filters: [{
property: 'Iteration.Name',
operator: '=',
value: iterationComboValue
}],
listeners: {
load: function(store, stories){
setOfStories = stories;
console.log('Iteration combo value is ', iterationComboValue);
console.log("# stories ",stories.length,stories);
}
}
});
async.map(configs, this.wsapiQuery, function(err,results){
setOfFeatures = results[0];
console.log("# features",setOfFeatures.length,setOfFeatures);
that.StartDate = that.startDate(iterations);
that.start = _.min(_.pluck(iterations,function(r) { return r.get("StartDate");}));
isoStart = new lumenize.Time(that.start).getISOStringInTZ("America/Chicago");
that.end = _.max(_.pluck(iterations,function(r) { return r.get("EndDate");}));
that.iterations = iterations;
//Here is the problem
setOfStories = results[1];
var stories = _.map(setOfStories, function(story){ return {name: story.get("Name"),fid: story.get("Feature").ObjectID,objectid: story.get("ObjectID")};}); //throws error
console.log('stories ',setOfStories);
var features = _.map(setOfFeatures, function(feature){return {name: feature.get("Name"), fid: feature.get("ObjectID")};});
console.log('features ',setOfFeatures);
var candidateStories = [];
_.each(stories, function(story){_.each(features, function(feature){
if(story.fid == feature){
candidateStories.push(story);
}
});});
console.log('candidate stories ',candidateStories.length,candidateStories);
if(candidateStories!=null){
that.getStorySnapShotsForFeatures(candidateStories);
}
//create snapshot store based on candidateStories.
});
},
getStorySnapShotsForFeatures: function(stories){
var snapshots = [];
var that = this;
async.map(stories, this.readStorySnapshots,function(err,results){
console.log('results ',results);
});
},
readStorySnapshots: function(parent,callback){
console.log('inside story snapshots ');
Ext.create('Rally.data.lookback.SnapshotStore',{
limit: 'Infinity',
autoLoad: true,
listeners:{
scope: this,
load: function(store,data,success){
callback(null,data);
}
},
fetch: ['ObjectID'],
filters:[{
property: 'ObjectID',
operator: 'in',
value: ['ObjectID']
},
{
property: '__At',
operator: '=',
value: 'current'
}]
});
},
startDate: function(iterations){
var start = _.min(_.pluck(iterations, function(r){return r.get("StartDate");}));
return Rally.util.DateTime.toIsoString(start, false);
}
});
In the async.map callback function, when setOfStories are returned, I try to map the name, fid, and objectID to a new array. But for some reason, the fid: story.get("Feature").ObjectID gives an error saying get("") is null. But just before returning the array, when I console log story.get("Feature").ObjectID the correct value is printed, but somehow when I try to return the same value, it generates an error.
The field on HierarchicalRequirement for its PI parent is called PortfolioItem (since the PI types are customizable- feature just happens to be the default name of the lowest level one).
story.get('PortfolioItem').ObjectID

Preselect items in EXT JS 4.2 Grid

I am trying to preselect items in my EXT grid based on the value of one of the items in the data store.
In my data store I fetch 7 items, the last item I grab 'installed' is a BOOLEAN and I would like to use that to preselect items in my grid.
Here is the code I have so far that is not working...
Ext.require([
'Ext.grid.*',
'Ext.data.*',
'Ext.selection.CheckboxModel'
]);
Ext.onReady(function(){
Ext.QuickTips.init();
var sb = $('#sb_id').val();
// Data store
var data = Ext.create('Ext.data.JsonStore', {
autoLoad: true,
fields: [ 'name', 'market', 'expertise', 'id', 'isFull', 'isPrimary', 'installed'],
proxy: {
type: 'ajax',
url: '/opsLibrary/getLibraryJsonEdit',
extraParams: {
sb_id: sb
},
actionMethods: 'POST'
},
sorters: [{
property: 'market',
direction: 'ASC'
}, {
property: 'expertise',
direction: 'ASC'
}]
});
data.on('load',function(records){
Ext.each(records,function(record){
var recs = [];
Ext.each(record, function(item, index){
console.log(item.data);
if (item.data['installed'] == true) {
console.log('Hi!');
recs.push(index);
}
});
//data.getSelectionModel().selectRows(recs);
})
});
// Selection model
var selModel = Ext.create('Ext.selection.CheckboxModel', {
columns: [
{xtype : 'checkcolumn', text : 'Active', dataIndex : 'id'}
],
listeners: {
selectionchange: function(value, meta, record, row, rowIndex, colIndex){
var selectedRecords = grid4.getSelectionModel().getSelection();
var selectedParams = [];
// Clear input and reset vars
$('#selected-libraries').empty();
var record = null;
var isFull = null;
var isPrimary = null;
// Loop through selected records
for(var i = 0, len = selectedRecords.length; i < len; i++){
record = selectedRecords[i];
// Is full library checked?
isFull = record.get('isFull');
// Is this primary library?
isPrimary = record.get('isPrimary');
// Build data object
selectedParams.push({
id: record.getId(),
full: isFull,
primary: isPrimary
});
}
// JSON encode object and set hidden input
$('#selected-libraries').val(JSON.stringify(selectedParams));
}}
});
I was trying to use an on.load method once the store was populated to go back and preselect my items but am not having any luck.
Im a Python guy and don't get around JS too much so sorry for the noobness.
Any help would be appreciated.
Thanks again!
You should be able to do something like:
//create selModel instance above
data.on('load', function(st, recs) {
var installedRecords = Ext.Array.filter(recs, function(rec) {
return rec.get('installed');
});
//selModel instance
selModel.select(installedRecords);
});
Select can take an array of records.
http://docs.sencha.com/extjs/4.2.1/#!/api/Ext.selection.Model-method-select
//data.getSelectionModel().selectRows(recs);
Didn't work because store's don't have a reference to selection models it is the other way around. You can get a selection model from a grid by doing grid.getSelectionModel() or
you can just use the selModel instance you created
var selModel = Ext.create('Ext.selection.CheckboxModel', {

How to remove field in websql

I have created a table in my websql using Sencha. Adding values to table works fine,
but removing doesn't work.
I've tried
getStore('favorite').removeAt(1);
but it gave no result. Are there are ways to handle sql requests like
"Delete from favorite where id = 1"
I've been Googling all day long. Any ideas? the code is below:
dockedItems: [
{
xtype: 'toolbar',
dock: 'top',
items: [
{
text: '+',
ui: 'decline',
handler: function(){
var s_name = post.get('list');
var s_image = post.get('image');
//var s_type = record.get('code');
//var c_content = post.get('filmpage');
//alert('РаботаетЬ');
Ext.require(['Ext.data.proxy.SQL']);
Ext.define("Favorite", {
extend: "Ext.data.Model",
config: {
fields: ["id","name","ftype","image","link","res"]
}
});
Ext.create("Ext.data.Store", {
model: "Favorite",
storeId: 'Favorite',
proxy: {
type: "sql"
}
});
var store = Ext.getStore('Favorite');
Ext.getStore('Favorite').removeAt(1);
Ext.getStore('Favorite').sync();
var record = Ext.getStore('Favorite').findExact('id', 1);
Ext.getStore('Favorite').remove(record);
Ext.getStore('Favorite').sync();
/*Ext.getStore('Favorite').add([{
name: s_name,
ftype: cat,
image: s_image,
link: '',
res : '',
}]);
Ext.getStore('Favorite').sync();*/
//Ext.getStore("Users").getModel("Users").getProxy("Users").dropTable("Favorite");
//Ext.getStore("Favorite").getModel("Ext.data.Model").getProxy().dropTable();
}
}
]
}
]
find solution using js that works, still thank you very much for your help.
db = openDatabase("Sencha", "1.0", "Sencha", 200000);
if(!db)
alert("Failed to connect to database.");
else
alert('yeah');
db.transaction(function(tx) {
tx.executeSql("DELETE FROM Favorite WhERE id = 3 ", [], function(result){}, function(tx, error){});
});
You should sync after removing record
var store = Ext.getStore('favorite');
store.removeAt(1);
store.sync();
Update
var index = store.findExact('id', 1);
store.remove(store.getAt(index));
store.sync();
How to debug
console.log(index); // Should return value 0 if there is a match else returns -1.
console.log(store.getAt(index)); // Should return the record with id value 1.

Resources