ExtJs 4: How do I create a dynamic menu? - dynamic

I have a menu system set up in a panel which needs to be dynamically created. I have created a mock static menu which the client likes but the menu categories and items will need to be loaded via JSON from a store.
Here is what I have for the first few menu items set statically:
Ext.define('SimpleSearch.view.FacetSDL' ,{
extend: 'Ext.panel.Panel',
alias : 'widget.facetsdl', //alias is referenced in MasterList.js
requires: ['SimpleSearch.store.SDLResults', 'FacetData' ],
title: 'Facet Search',
html: null,
frame: true,
layouts: 'fit',
items: [
{
id: 'group-menu',
title: 'Browse',
xtype: 'menu',
plain: true,
floating: false,
layouts: 'fit',
items: [
{
text: 'Security',
listeners:
{
click: function() {
var groupmenu = Ext.ComponentQuery.query('#group-menu')[0];
groupmenu.hide()
var securitymenu = Ext.ComponentQuery.query('#security-menu')[0];
securitymenu.setPosition(0,-groupmenu.getHeight(),false);
securitymenu.show()
}
},
menu: { // <-- submenu by nested config object
items: [
{
text: 'Classification',
listeners:
{
click: function() {
var groupmenu = Ext.ComponentQuery.query('#group-menu')[0];
groupmenu.hide()
var securitymenu = Ext.ComponentQuery.query('#security-menu')[0];
var classificationmenu = Ext.ComponentQuery.query('#classification-menu')[0];
classificationmenu.setPosition(0,-groupmenu.getHeight() - securitymenu.getHeight(),false);
classificationmenu.show()
}
I was thinking that maybe creating a class that loads all of the necessary data and then iterating through that class for the "items" field may be the way to go, but I am not sure if that will work.

You should look at using a Tree and TreeStore. Then make use of the ui:'menu' or viewConfig { ui: 'menu' } config properties to differentiate it from a regular tree. Then style it however your client wants.
This way you have all the mechanisms in place for free to handle the data dynamically and all your submenus, you'll just have to get a little creative on the CSS side of things.

I got it working like this:
var scrollMenu = Ext.create('Ext.menu.Menu');
for (var i = 0; i < store.getCount(); ++i){
var rec = store.getAt(i);
var item = new Ext.menu.Item({
text: rec.data.DISPLAY_FIELD,
value:rec.data.VALUE_FIELD,
icon: 'js/images/add.png',
handler: function(item){
myFunction(item.value); //Handle the item click
}
});
scrollMenu.add(item);
}
Then just add scrollMenu to your form or container. Hope this helps!

This menu is created dynamically with ExtJs, the data is loaded from Json.
See my demo with the code.
Demo Online:
https://fiddle.sencha.com/#view/editor&fiddle/2vcq
Json loaded:
https://api.myjson.com/bins/1d9tdd
Code ExtJs:
//Description: ExtJs - Create a dynamical menu from JSON
//Autor: Ronny Morán <ronney41#gmail.com>
Ext.application({
name : 'Fiddle',
launch : function() {
var formPanelFMBtn = Ext.create('Ext.form.Panel', {
bodyPadding: 2,
waitMsgTarget: true,
fieldDefaults: {
labelAlign: 'left',
labelWidth: 85,
msgTarget: 'side'
},
items: [
{
xtype: 'container',
layout: 'hbox',
items: [
]
}
]
});
var win = Ext.create('Ext.window.Window', {
title: 'EXTJS DYNAMICAL MENU FROM JSON',
modal: true,
width: 680,
closable: true,
layout: 'fit',
items: [formPanelFMBtn]
}).show();
//Consuming JSON from URL using method GET
Ext.Ajax.request({
url: 'https://api.myjson.com/bins/1d9tdd',
method: 'get',
timeout: 400000,
headers: { 'Content-Type': 'application/json' },
//params : Ext.JSON.encode(dataJsonRequest),
success: function(conn, response, options, eOpts) {
var result = Ext.JSON.decode(conn.responseText);
//passing JSON data in 'result'
viewMenuDinamical(formPanelFMBtn,result);
},
failure: function(conn, response, options, eOpts) {
//Ext.Msg.alert(titleAlerta,msgErrorGetFin);
}
});
}
});
//Generate dynamical menu with data from JSON
//Params: formPanelFMBtn - > Panel
// result - > Json data
function viewMenuDinamical(formPanelFMBtn,result){
var resultFinTarea = result;
var arrayCategoriaTareas = resultFinTarea.categoriaTareas;
var containerFinTarea = Ext.create('Ext.form.FieldSet', {
xtype: 'fieldset',
title: 'Menu:',
margins:'0 0 5 0',
flex:1,
layout: 'anchor',
//autoHeight: true,
autoScroll: true,
height: 200,
align: 'stretch',
items: [
]
});
var arrayMenu1 = [];
//LEVEL 1
for(var i = 0; i < arrayCategoriaTareas.length; i++)
{
var categoriaPadre = arrayCategoriaTareas[i];
var nombrePadre = categoriaPadre.nombreCategoria;
var hijosPadre = categoriaPadre.hijosCategoria;
var arrayMenu2 = [];
//LEVEL 2
for(var j = 0; j<hijosPadre.length; j++)
{
var categoriaHijo = hijosPadre[j];
var nombreHijo = categoriaHijo.nombreHijo;
var listaTareas = categoriaHijo.listaTareas;
var arrayMenu3 = [];
//LEVEL 3
for(var k = 0; k < listaTareas.length; k++)
{
var tarea = listaTareas[k];
var nombreTarea = tarea.nombreTarea;
var objFinLTres =
{
text: nombreTarea,
handler: function () {
alert("CLICK XD");
}
};
arrayMenu3.push(objFinLTres);
}
var menuLevel3 = Ext.create('Ext.menu.Menu', {
items: arrayMenu3
});
var objFinLDos;
if(arrayMenu3.length > 0)
{
objFinLDos = {
text: nombreHijo,
menu:menuLevel3
};
}
else
{
//without menu parameter If don't have children
objFinLDos = {
text: nombreHijo
};
}
arrayMenu2.push(objFinLDos);
}
var menuLevel2 = Ext.create('Ext.menu.Menu', {
items: arrayMenu2
});
var objFinLUno;
if(arrayMenu2.length > 0)
{
objFinLUno = {
text: nombrePadre,
menu:menuLevel2
};
}
else
{
//without menu parameter If don't have children
objFinLUno = {
text: nombrePadre
};
}
arrayMenu1.push(objFinLUno);
}
var mymenu = new Ext.menu.Menu({
items: arrayMenu1
});
containerFinTarea.add({
xtype: 'splitbutton',
text: 'Example xD',
menu: mymenu
});
formPanelFMBtn.add(containerFinTarea);
}

Related

Using a custom Drop Down List field to set a value in a grid

I'm trying to use the Rally 2.1 SDK to set a custom data field (c_wsjf) in a grid. I have a custom drop down list that I want to check the value of (c_TimeCrticalitySizing).
I created c_TimeCrticalitySizing as a feature card field in my Rally workspace with different string values (such as "No decay"). Every drop down list value will set the custom field to a different integer. When I try to run the app in Rally I get this error:
"Uncaught TypeError: Cannot read property 'isModel' of undefined(…)"
I'm thinking the drop down list value may not be a string.
How would I check what the type of the drop down list value is?
How could I rewrite this code to correctly check the value of the drop down list so I can set my custom field to different integers?
Here's my code block for the complete app. I'm still trying to hook up a search bar so for now I directly call _onDataLoaded() from the launch() function.
// START OF APP CODE
Ext.define('CustomApp', {
extend: 'Rally.app.App',
componentCls: 'app',
featureStore: undefined,
featureGrid: undefined,
items: [ // pre-define the general layout of the app; the skeleton (ie. header, content, footer)
{
xtype: 'container', // this container lets us control the layout of the pulldowns; they'll be added below
itemId: 'widget-container',
layout: {
type: 'hbox', // 'horizontal' layout
align: 'stretch'
}
}
],
// Entry point of the app
launch: function() {
var me = this;
me._onDataLoaded();
},
_loadSearchBar: function() {
console.log('in loadsearchbar');
var me = this;
var searchComboBox = Ext.create('Rally.ui.combobox.SearchComboBox', {
itemId: 'search-combobox',
storeConfig: {
model: 'PortfolioItem/Feature'
},
listeners: {
ready: me._onDataLoaded,
select: me._onDataLoaded,
scope: me
}
});
// using 'me' here would add the combo box to the app, not the widget container
this.down('#widget-container').add(searchComboBox); // add the search field to the widget container <this>
},
// If adding more filters to the grid later, add them here
_getFilters: function(searchValue){
var searchFilter = Ext.create('Rally.data.wsapi.Filter', {
property: 'Search',
operation: '=',
value: searchValue
});
return searchFilter;
},
// Sets values once data from store is retrieved
_onDataLoaded: function() {
console.log('in ondataloaded');
var me = this;
// look up what the user input was from the search box
console.log("combobox: ", this.down('#search-combobox'));
//var typedSearch = this.down('#search-combobox').getRecord().get('_ref');
// search filter to apply
//var myFilters = this._getFilters(typedSearch);
// if the store exists, load new data
if (me.featureStore) {
//me.featureStore.setFilter(myFilters);
me.featureStore.load();
}
// if not, create it
else {
me.featureStore = Ext.create('Rally.data.wsapi.Store', {
model: 'PortfolioItem/Feature',
autoLoad: true,
listeners: {
load: me._createGrid,
scope: me
},
fetch: ['FormattedID', 'Name', 'TimeCriticality',
'RROEValue', 'UserBusinessValue', 'JobSize', 'c_TimeCriticalitySizing']
});
}
},
// create a grid with a custom store
_createGrid: function(store, data){
var me = this;
var records = _.map(data, function(record) {
//Calculations, etc.
console.log(record.get('c_TimeCriticalitySizing'));
var timecritsize = record.get('c_TimeCriticalitySizing');
//console.log(typeof timecritsize);
var mystr = "No decay";
var jobsize = record.get('JobSize');
var rroe = record.get('RROEValue');
var userval = record.get('UserBusinessValue');
var timecrit = record.get('TimeCriticality');
// Check that demoniator is not 0
if ( record.get('JobSize') > 0){
if (timecritsize === mystr){
var priorityScore = (timecrit + userval + rroe) / jobsize;
return Ext.apply({
c_wsjf: Math.round(priorityScore * 10) / 10
}, record.getData());
}
}
else{
return Ext.apply({
c_wsjf: 0
}, record.getData());
}
});
// Add the grid
me.add({
xtype: 'rallygrid',
showPagingToolbar: true,
showRowActionsColumn: true,
enableEditing: true,
store: Ext.create('Rally.data.custom.Store', {
data: records
}),
// Configure each column
columnCfgs: [
{
xtype: 'templatecolumn',
text: 'ID',
dataIndex: 'FormattedID',
width: 100,
tpl: Ext.create('Rally.ui.renderer.template.FormattedIDTemplate')
},
{
text: 'WSJF Score',
dataIndex: 'c_wsjf',
width: 150
},
{
text: 'Name',
dataIndex: 'Name',
flex: 1,
width: 100
}
]
});
}
});
// END OF APP CODE
The app works great until I add the if (timecritsize === mystr) conditional.
I also use console.log() to check that I've set all values for timecritsize to "No decay"

List doesn't show after android native build application

I have Ext.dataview.List, I successfully can see it in my browser. But after buildind my application for android list and it's title doesn't shown. I tried almost everything but noghing helps.
Here is my code:
MenuTabPanel.js:
Ext.define('App.view.MenuTabPanel', {
extend: 'Ext.tab.Panel',
xtype: 'menutb',
requires: [
'Ext.TitleBar',
'Ext.dataview.List'
],
config: {
tabBarPosition: 'bottom',
fullscreen : true,
id: 'menuTabPanel',
//layout: 'fit',
listeners: {
painted : function(element, eOpts) {
if(this.getActiveItem()) {
var title = this.getActiveItem().child('[xtype=list]').title;
var navBar = Ext.getCmp('navMenu').getNavigationBar();
navBar.setTitle(title);
}
}
}
},
initialize: function() {
var content = [];
//var menuStore = Ext.getStore('menuItemsStore');
var menuStore = Ext.create('App.store.MenuItemsStore');
var onMenuItemClicked = function(list, index, node,record){
var navigateTo = Ext.create('App.view.' + record.get('Id') + 'View');
var navMenu = Ext.getCmp('navMenu');
navMenu.push(navigateTo);
};
var tabPanel = this;
var onStoreLoad = function(){
menuStore.filter("Level",1);
menuStore.each(function(record) {
var tabItem = {};
var items = {};
tabItem['iconCls'] = record.get('Id');
tabItem['layout'] = 'fit';
items['id'] = record.get('Id');
items['title'] = record.get('Title');
items['xtype'] = 'list';
items['height'] = '100%';
items['width'] = '100%';
//items['layout'] = 'vbox';
//items['flex'] = 1;
items['itemTpl'] = '<div class="menuitem-text"><img src="../resources/icons/{Id}.png" /> {Title}</div>';
//items['store'] = Ext.getStore('menuItemsStore');
var listen = {};
listen['itemtap'] = onMenuItemClicked;
items['listeners'] = listen;
tabItem['items'] = [items];
content.push(tabItem);
}
);
tabPanel.add(content);
}
menuStore.load(onStoreLoad);
this.callParent(arguments);
}
});
MenuController.js:
Ext.define('App.controller.MenuController', {
extend: 'Ext.app.Controller',
requires: [
'Ext.dataview.List'
],
config: {
control: {
"menutb": {
activeitemchange: 'onTabPanelActiveItemChange'
}
}
},
onTabPanelActiveItemChange: function(othis, value, oldValue, eOpts) {
var list = value.child('[xtype=list]');
var mainStore = Ext.getStore('menuItemsStore');
var results = mainStore.queryBy(function(rec){
if(rec.get('Level') == 2 && rec.get('Parent') == list.title)
return true;
});
var data1 = Ext.Array.pluck(results.getRange(), 'data');
list.setStore({
model: 'Mobile.model.MenuItem',
data: data1
});
var navBar = othis.getParent().getNavigationBar();
navBar.setTitle(list.title);
}
});
MenuView.js:
Ext.define('App.view.MenuView', {
extend: 'Ext.NavigationView',
xtype: 'menu',
requires: [
'Ext.TitleBar',
'Ext.dataview.List',
'App.view.MenuTabPanel'
],
config: {
id: 'navMenu',
items: [{
xtype: 'menutb'
}
]
}
});
My app starts from MenuView.js.
What I am doing wrong or what I miss? Or maybe it is problem in android with Lists?
Edited:
I find out that there is some problem with activeitemchange event, it fires after initialize. When I commented this event list normally is shown on android. Also when I don't load store and write manually data, the event fires normally.

Sencha and localStorage

Morning,
I'm new to Sencha. I have the following code in my login.js, which retrieves form fields from a JSON doc on remove server. It creates an array from the data, which I need tro be able to use to populate the form:
var url = 'http://domainxxx.net/';
loginFields = new Array();
Ext.onReady(function(){var theform = Ext.Ajax.request({
url: url+'login',
type: 'get',
scope: this,
dataType: "JSON",
success: function(response){
formFields = new Array();
var numFields = Ext.JSON.decode(response.responseText).length;
for (var inf=0;inf<numFields;inf++){
afield = new Array();
afield['xtype'] = 'textfield';
afield['name'] = Ext.JSON.decode(response.responseText)[inf].Name;
afield['itemId'] = Ext.JSON.decode(response.responseText)[inf].Name;
afield['required'] = true;
afield['description'] = Ext.JSON.decode(response.responseText)[inf].Description;
afield['placeHolder'] = Ext.JSON.decode(response.responseText)[inf].Description;
afield['maxlength'] = Ext.JSON.decode(response.responseText)[inf].Length;
if(Ext.JSON.decode(response.responseText)[inf].Type == 1){afield['xtype']= 'passwordfield';}
if(Ext.JSON.decode(response.responseText)[inf].Type == 0){afield['xtype']= 'emailfield';}
loginFields.push(afield);
}
console.log(loginFields);
}
})
});
The problem is then using this variable to populate the form. I tried placing it in the form config, as shown below, but no luck. I also tried using localStorage, but that didn't work either.
Ext.define('axis3.view.Login', {
extend: 'Ext.form.Panel',
alias: "widget.loginview",
requires: ['Ext.form.FieldSet', 'Ext.form.Password', 'Ext.Label', 'Ext.Img'], config: {
title: 'Login',
itemId: 'loginform',
items: [
{
xtype: 'image',
src: Ext.Viewport.getOrientation() == 'portrait' ? 'images/logo.png' : 'images/logo.png',
style: Ext.Viewport.getOrientation() == 'portrait' ? 'width:271px;height:93px;margin:2em auto' : 'width:271px;height:93px;margin:2em auto'
},
{
xtype: 'label',
html: 'Login failed. Please enter the correct credentials.',
itemId: 'signInFailedLabel',
hidden: true,
hideAnimation: 'fadeOut',
showAnimation: 'fadeIn',
style: 'color:#990000;margin:5px 0px;'
},
{
xtype: 'fieldset',
title: 'Login',
items: [
FORM VARIABLES IN HERE
]
},
{
xtype: 'button',
itemId: 'logInButton',
ui: 'action',
padding: '10px',
text: 'Log In'
}
],
listeners: [{............
Any advice is most welcome
You are using an Array instead of an Object. Rather than saying var aField = new Array(), say var aField = new Object().
Note that, for short hand, you can also do this instead of using a constructor:
var myArray = [];
car myObject = {};

ExtJs3.4.0 to ExtJs4.1.1 upgrade issues

ExtJS4: I am having problems while upgrading my application ExtJs version from 3.4.0 to 4.1.1a.
My 3.4.0 version code:
this.jsonStore = new Ext.data.JsonStore({
proxy : new Ext.data.HttpProxy({
url: 'rs/environments',
disableCaching: true
}),
restful : true,
storeId : 'Environments',
idProperty: 'env',
fields : [
'ConnectionName', 'Type'
]
});
this.colmodel = new Ext.grid.ColumnModel({
defaults: {
align: 'center'
},
columns: [{
header: Accero.Locale.text.adminlogin.connectionsHeading,
width : 140,
dataIndex: 'ConnectionName'
},
{
header: Accero.Locale.text.adminlogin.connectionTypeHeader,
width : 120,
dataIndex: 'Type'
}]
});
config = Ext.apply({
enableHdMenu: false,
border : true,
stripeRows : true,
store : this.jsonStore,
view : new Ext.grid.GridView(),
header : false,
colModel : this.colmodel,
sm : new Ext.grid.RowSelectionModel({singleSelect: true}),
loadMask: {
msg: Accero.Locale.text.adminlogin.loadingmask
}
}, config);
I made below changes to make application work with ExtJs4.1.1:
var sm = new Ext.selection.CheckboxModel( {
listeners:{
selectionchange: function(selectionModel, selected, options){
// Must refresh the view after every selection
myGrid.getView().refresh();
// other code for this listener
}
}
});
var getSelectedSumFn = function(column){
return function(){
var records = myGrid.getSelectionModel().getSelection(),
result = 0;
Ext.each(records, function(record){
result += record.get(column) * 1;
});
return result;
};
}
var config = Ext.create('Ext.grid.Panel', {
autoScroll:true,
features: [{
ftype: 'summary'
}],
store: this.jsonStore,
defaults: { // defaults are applied to items, not the container
sortable:true
},
selModel: sm,
columns: [
{header: Accero.Locale.text.adminlogin.connectionsHeading, width: 140, dataIndex: 'ConnectionName'},
{header: Accero.Locale.text.adminlogin.connectionTypeHeader, width: 120, dataIndex: 'Type'}
],
loadMask: {
msg: Accero.Locale.text.adminlogin.loadingmask
},
viewConfig: {
stripeRows: true
}
}, config);
With these changes, I am getting the error at my local file 'ext-override.js' saying 'this.el is not defined'.
I debug the code and found that, in the current object this, there is no el object.
ext-override.js code:
(function() {
var originalInitValue = Ext.form.TextField.prototype.initValue;
Ext.override(Ext.form.TextField, {
initValue: function() {
originalInitValue.apply( this, arguments );
if (!isNaN(this.maxLength) && (this.maxLength *1) > 0 && (this.maxLength != Number.MAX_VALUE)) {
this.el.dom.maxLength = this.maxLength *1;
}
}
}
);
})();
Kindly suggest where am I going wrong?
Thanks in advance...
Seriously, use more lazy initialization! Your code is a hell of objects, all unstructured.
First of all, you can override and use the overridden method more easily with something like that (since 4.1)
Ext.override('My.Override.for.TextField', {
override : 'Ext.form.TextField',
initValue: function() {
this.callOverridden(arguments);
if (!isNaN(this.maxLength) && (this.maxLength *1) > 0 && (this.maxLength != Number.MAX_VALUE)) {
this.el.dom.maxLength = this.maxLength *1;
}
}
});
But: The method initValue is called in initField (and this in initComponent) so that you cannot have a reference to this.me because the component is actually not (fully) rendered.
So, this should help (not tested):
Ext.override('My.Override.for.TextField', {
override : 'Ext.form.TextField',
afterRender: function() {
this.callOverridden(arguments);
if (!isNaN(this.maxLength) && (this.maxLength *1) > 0 && (this.maxLength != Number.MAX_VALUE)) {
this.el.dom.maxLength = this.maxLength *1;
}
}
});
But I'm strongly recommend not to use such things within overrides. Make dedicated components which will improve code readibility.

how to set variable value from the server response extjs 4

forum member I am having one problem in setting the value of my view from the server response I am receiving
I am using the MVC architechture of the extjs 4. My store is loaded perfectly and my taskstore is defined as below
Ext.define('gantt.store.taskStore', {
extend: 'Gnt.data.TaskStore',
model: 'gantt.model.ResourceTask',
storeId: 'taskStore',
autoLoad : true,
autoSync : true,
proxy : {
type : 'ajax',
api: {
read: 'task/GetTask.action',
create: 'task/CreateTask.action',
destroy: 'task/DeleteTask.action',
update: 'task/UpdateTask.action'
},
writer : new Ext.data.JsonWriter({
//type : 'json',
root : 'taskdata',
encode : true,
writeAllFields : true
}),
reader : new Ext.data.JsonReader({
totalPropery: 'total',
successProperty : 'success',
idProperty : 'id',
type : 'json',
root: function (o) {
if (o.taskdata) {
return o.taskdata;
} else {
return o.children;
}
}
})
}
});
but what I want to do is that as soon as the store loaded I want to assign the server response data to one of the variable in my javascript.
I tried to add the value from the beforeload function of view, but not able to do so.
my view code is given as below
var result = Ext.JSON.decode('{"calendardata": [{"startdate": 1330281000000,"enddate": 1330284600000,"id": 3,"title": "mon"}],"total": 1,"success": true}');
//var start = new Date(2012, 2, 26),
//end = Sch.util.Date.add(start, Sch.util.Date.MONTH, 30);
var start_d = new Date(result.calendardata[0].startdate);
var end_d = new Date(result.calendardata[0].enddate);
var start = new Date(start_d.getFullYear(), start_d.getMonth(), start_d.getDate());
end = Sch.util.Date.add(start, Sch.util.Date.MONTH, 30);
console.log("YEAR ::"+start.getFullYear()+"MONTH ::"+start.getMonth()+"DAY ::"+start.getDate());
console.log("YEAR ::"+end.getFullYear()+"MONTH ::"+end.getMonth()+"DAY ::"+end.getDate());
//create the downloadframe at the init of your app
this.downloadFrame = Ext.getBody().createChild({
tag: 'iframe'
, cls: 'x-hidden'
, id: 'iframe'
, name: 'iframe'
});
//create the downloadform at the init of your app
this.downloadForm = Ext.getBody().createChild({
tag: 'form'
, cls: 'x-hidden'
, id: 'form'
, target: 'iframe'
});
var printableMilestoneTpl = new Gnt.template.Milestone({
prefix : 'foo',
printable : true,
imgSrc : 'resources/images/milestone.png'
});
var params = new Object();
Ext.define('gantt.view.projectmgt.projectGanttpanel', {
extend: "Gnt.panel.Gantt",
id: 'projectganttpanel',
alias: 'widget.projectganttpanel',
requires: [
'Gnt.plugin.TaskContextMenu',
'Gnt.column.StartDate',
'Gnt.column.EndDate',
'Gnt.column.Duration',
'Gnt.column.PercentDone',
'Gnt.column.ResourceAssignment',
'Sch.plugin.TreeCellEditing',
'Sch.plugin.Pan',
'gantt.store.taskStore',
'gantt.store.dependencyStore'
],
leftLabelField: 'Name',
loadMask: true,
//width: '100%',
// height: '98%',
startDate: start,
endDate: end,
multiSelect: true,
cascadeChanges: true,
viewPreset: 'weekAndDayLetter',
recalculateParents: false,
showTodayLine : true,
showBaseline : true,
initComponent: function() {
var me = this;
me.on({
scope: me,
beforeload: function(store,records,options) {
console.log('BEFORE LOAD YAAR panel'+records.params);
if(records.params['id'] != null)
{
return true;
}
else
{
return false;
}
}
});
TaskPriority = {
Low : 0,
Normal : 1,
High : 2
};
var taskStore = Ext.create('gantt.store.taskStore');
var dependencyStore = Ext.create('gantt.store.dependencyStore');
Ext.apply(me, {
taskStore: taskStore,
dependencyStore: dependencyStore,
// Add some extra functionality
plugins : [
Ext.create("Gnt.plugin.TaskContextMenu"),
Ext.create('Sch.plugin.TreeCellEditing', {
clicksToEdit: 1
}),
Ext.create('Gnt.plugin.Printable', {
printRenderer : function(task, tplData) {
if (task.isMilestone()) {
return;
} else if (task.isLeaf()) {
var availableWidth = tplData.width - 4,
progressWidth = Math.floor(availableWidth*task.get('PercentDone')/100);
return {
// Style borders to act as background/progressbar
progressBarStyle : Ext.String.format('width:{2}px;border-left:{0}px solid #7971E2;border-right:{1}px solid #E5ECF5;', progressWidth, availableWidth - progressWidth, availableWidth)
};
} else {
var availableWidth = tplData.width - 2,
progressWidth = Math.floor(availableWidth*task.get('PercentDone')/100);
return {
// Style borders to act as background/progressbar
progressBarStyle : Ext.String.format('width:{2}px;border-left:{0}px solid #FFF3A5;border-right:{1}px solid #FFBC00;', progressWidth, availableWidth - progressWidth, availableWidth)
};
}
},
beforePrint : function(sched) {
var v = sched.getSchedulingView();
this.oldRenderer = v.eventRenderer;
this.oldMilestoneTemplate = v.milestoneTemplate;
v.milestoneTemplate = printableMilestoneTpl;
v.eventRenderer = this.printRenderer;
},
afterPrint : function(sched) {
var v = sched.getSchedulingView();
v.eventRenderer = this.oldRenderer;
v.milestoneTemplate = this.oldMilestoneTemplate;
}
})
],
eventRenderer: function (task) {
var prioCls;
switch (task.get('Priority')) {
case TaskPriority.Low:
prioCls = 'sch-gantt-prio-low';
break;
case TaskPriority.Normal:
prioCls = 'sch-gantt-prio-normal';
break;
case TaskPriority.High:
prioCls = 'sch-gantt-prio-high';
break;
}
return {
cls: prioCls
};
},
// Setup your static columns
columns: [
{
xtype : 'treecolumn',
header: 'Tasks',
dataIndex: 'Name',
width: 150,
field: new Ext.form.TextField()
},
new Gnt.column.StartDate(),
new Gnt.column.Duration(),
new Gnt.column.PercentDone(),
{
header: 'Priority',
width: 50,
dataIndex: 'Priority',
renderer: function (v, m, r) {
switch (v) {
case TaskPriority.Low:
return 'Low';
case TaskPriority.Normal:
return 'Normal';
case TaskPriority.High:
return 'High';
}
}
},
{
xtype : 'booleancolumn',
width : 50,
header : 'Manual',
dataIndex : 'ManuallyScheduled',
field : {
xtype : 'combo',
store : [ 'true', 'false' ]
}
}
],
tooltipTpl: new Ext.XTemplate(
'<h4 class="tipHeader">{Name}</h4>',
'<table class="taskTip">',
'<tr><td>Start:</td> <td align="right">{[Ext.Date.format(values.StartDate, "y-m-d")]}</td></tr>',
'<tr><td>End:</td> <td align="right">{[Ext.Date.format(Ext.Date.add(values.EndDate, Ext.Date.MILLI, -1), "y-m-d")]}</td></tr>',
'<tr><td>Progress:</td><td align="right">{PercentDone}%</td></tr>',
'</table>'
).compile()
});
me.callParent(arguments);
}
});
the reason I am not able to set the value of variable I used to set it using static data. To set the static data I am using the below code
var result = Ext.JSON.decode('{"calendardata": [{"startdate": 1330281000000,"enddate": 1330284600000,"id": 3,"title": "mon"}],"total": 1,"success": true}');
var start_d = new Date(result.calendardata[0].startdate);
var end_d = new Date(result.calendardata[0].enddate);
var start = new Date(start_d.getFullYear(), start_d.getMonth(), start_d.getDate());
end = Sch.util.Date.add(start, Sch.util.Date.MONTH, 30);
but instead of this static data I want to set the start and end value as soon as the store loads and server response is received.
please suggest me some solution I can apply here.
I am receiving the jsondata as
{
"taskdata": [{
"startdate": 1330281000000,
"enddate": 1330284600000,
"id": 3,
"title": "mon"
}],
"total": 1,
"success": true
}
I am using extjs 4 with MVC architecture and JAVA as my server side technology.
First of all your question is kind of badly formulated. You have too much code and not really clear what are you trying to ask. In a future try to isolate a particular problem you're dealing with if you want to get quick and proper answer.
Second, load operation is asynchronous. You just specified store as 'autoLoad', but I don't see anywhere where you subscribe to its load event. Most likely your problem is trying to get something of the store while it's not yet loaded. Try to set autoLoad: false, load store manually and subscribe to its 'load' event to populate your view.