Extjs 4 How to get id of parent Component? - extjs4

I have multiple fieldset. And have Button inside each fieldset in Extjs 4.
I want to get fieldset id on the button click event, so that i can know from which fieldset the button was clicked
How do i get this?
{
xtype:'fieldset',
id:'fs1',
items:[{
xtype:'button',
id:'b1',
handler:function(){
// here i want to get fieldset's id because because fieldset and button were added dynamically.
}
}]
}
Thanks,
Kunal
Actual Code:
Ext.define('My.Group',{
xtype : 'fieldset',
config: {
title:'Group' + i.toString(),
id : '_group' + i.toString()
},
constructor: function(config) {
this.initConfig(config);
return this;
},
collapsible : true,
frame : false,
boder : false,
items : [ {
xtype : 'button',
text : 'Add KeyWord',
id: 'btn',
width : 100,
handler : function(button,event) {
var fieldset = button.findParentByType('fieldset');
var fieldsetsID = fieldset.getId();
console.log(fieldset);
Ext.getCmp(fieldsetId).insert(2, rangeField);
Ext.getCmp(fieldsetsID).doLayout();
}
}, {
xtype : 'button',
text : 'Add Range Type',
width : 100
} ]
});
and i am calling this function on button click
handler : function() {
i=i+1;
var group = new My.Group({
title:'Group' + i.toString(),
id : '_group' + i.toString()
});
console.log(group);
Ext.getCmp('_aspanel').insert(i, group);
Ext.getCmp('_aspanel').doLayout();

I've implemented handler properly.
{
xtype:'fieldset',
id:'fs1',
items:[{
xtype:'button',
id:'b1',
handler:function(btn){
// Retrieve fieldset.
var fieldset = btn.up('fieldset');
// Retrieve Id of fieldset.
var fieldsetId = fieldset.getId();
}
}]
}
In that case try this:
button.up("[xtype='fieldset']")

Ext.onReady(function() {
var panel = Ext.create('Ext.panel.Panel', {
items: {
xtype:'fieldset',
id:'fs1',
items:[{
xtype:'button',
id:'b1',
handler:function(b,e){
var fieldset = b.findParentByType('fieldset');
var fieldsetID = fieldset.getId();
console.log(fieldsetID);
}
}]
},
renderTo: document.body
});
});
Notice, that once you have fieldset variable, you can actually add items to this container directly, without need to use its ID

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"

Failed to change the text of a titlebar in a container with sencha touch 2.1

I want to create an application with users login and logout. When the user logs in ,the system will store the user information such as username,sessionid into the localstorage and then go to the index page. The index page has a titlebar with username on the left and a button to log out.But it failed to get the data stored in the localstorage that was stored when a user logs in when the index page appears.
My code is as below:
index page:
Ext.define('MyApp.view.MyPanel', {
extend : 'Ext.Panel',
id : 'myPanel',
config : {
xtype : 'panel',
layout : 'vbox',
height : '100%',
width : '100%',
items : [
{
xtype : 'titlebar',
docked : 'top',
title : 'my panel',
items : [
{
align : 'left',
id : 'portal-username',
text : 'qq' //i used localStorage.getItem('userName') first,but not as good.
},
{
align : 'right',
text : 'log out',
listeners : {
tap : function(){
var userName=null;var rememberPassword=null;var password=null;
if(userName=Ext.getCmp('userName'))userName.setValue('');
if(password=Ext.getCmp('password'))password.setValue('');
if(rememberPassword=Ext.getCmp('rememberPassword'))rememberPassword.setChecked(false);
//localstorage
localStorage.removeItem('userName','');
localStorage.removeItem('password','');
localStorage.removeItem('SessionId','');
localStorage.removeItem('rememberPassword','');
var oldp=Ext.getCmp('loginPanel');if(oldp)oldp.destroy();
var newActivePanel = Ext.create('MyApp.view.LoginPanel');
Ext.Viewport.add(newActivePanel);
Ext.Viewport.animateActiveItem(newActivePanel,{type:'slide',direction:'left'});
}
}
}
]
}
]
}
});
part of login panel:
items : [
{
xtype : 'button',
text : 'login',
ui : 'action',
handler : function() {
var userName = Ext.getCmp('userName').getValue();
var password = Ext.getCmp('password').getValue();
var rememberPassword = Ext.getCmp('rememberPassword').getChecked()+ '';
if(!userName||!password){
Ext.Msg.alert('prompt','login failure,try again!',Ext.emptyFn);
}
else Ext.Ajax.request({
url : remoteServer,
params : {
loginName: userName,
passWord : password,
SessionId : localStorage.getItem('SessionId');
},
method : 'POST',
callback : function(options,success,response) {
if (success) {
var result = Ext.JSON.decode(response.responseText.trim());
var status = result.status;
if (status == 'success') {
if (rememberPassword == 'true')
localStorage.setItem('rememberPassword',rememberPassword);
localStorage.setItem('userName',userName);
localStorage.setItem('password',password);
localStorage.setItem('SessionId',result.SessionId);
var oldp=Ext.getCmp('MyPanel');if(oldp)oldp.destroy();
var newActivePanel = Ext.create('MyApp.view.MyPanel');
Ext.Viewport.add(newActivePanel);
Ext.Viewport.animateActiveItem(newActivePanel,{type:'slide',direction:'left'});
} else {
localStorage.setItem('userName','');
localStorage.setItem('password','');
localStorage.setItem('JSessionId','');
localStorage.setItem('rememberPassword','');
Ext.Msg.alert('prompt','login failure,try again!',Ext.emptyFn);
}
} else {
Ext.Msg.alert('prompt','login failure,try again!',Ext.emptyFn);
}
}
});
}
}
]
Below is my controller :
Ext.define('MyApp.controller.MyController',
{
extend : 'Ext.app.Controller',
id : 'MyController',
config : {
control : {
MyPanel : {
show : 'panelActive'
},
},
refs : {
MyPanel : '#myPanel'
}
}//config
,panelActive : function(){
Ext.getCmp('portal-username').setText(localStorage.getItem('userName'));
}
});
After Following line
Ext.Viewport.animateActiveItem(newActivePanel,{type:'slide',direction:'left'});
in login handler function just set the username using
Ext.getCmp('portal-username').setText(userName);

Using createDelegate in extjs

Here is my first try to pass user defined arguments to a handler function in extjs(4.0.1) in IE9. I have the below code, but it throws up an error stating that SCRIPT438: Object doesn't support property or method 'createDelegate'. I'm not sure what I'm doing wrong. Please help.
Js file:
Ext.onReady(function() {
var appendBooleanOrInsertionIndex = 0;
var myButtonHandler = function(item,a, b, arg){
alert(a + " "+ b);
};
var myButton = new Ext.Button({
id : 'myButton',
//renderTo : 'mybutton',
text : 'Save',
handler : myButtonHandler.createDelegate(this, ['Hi', 'Kart'], appendBooleanOrInsertionIndex),
scope : this
});
});
Ext stopped adding logic to native class prototypes in Ext 4. Use Ext.Function.bind or Ext.Function.pass.
the corrected code is as below:
Ext.onReady(function() {
var myButtonHandler = function(a, b){//alert("-->");
alert(a + " "+ b);
};
Ext.create('Ext.panel.Panel', {
renderTo: Ext.getBody(),
width: 800,
height: 300,
layout: 'column',
title: 'Container Panel',
//html: 'parent panel',
items: [
{
xtype: 'button',
id: 'mbutton',
text : 'My Button',
handler : Ext.Function.pass(myButtonHandler, ['Hi', 'Kart!!!!'])
}
]
});
});

ExtJs 4: How do I create a dynamic menu?

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);
}

Sencha touch: cannot get reference to items in panel

I'm am trying to get MVC to work in my first application and am trying to change cards based button clicked in toolbar.
I'm getting a runtime error when I click the hello or world button in the toolbar: TypeError: Cannot read property 'items' of undefined on the line:
var exerciseListPanel = this.items.items[0], // CODE ERRORS HERE!
I'm having a problem in getting a reference to the items in the panel, WHY?
Here is the complete code for the panel:
MyApp.views.HomeScreenPanel = Ext.extend(Ext.Panel, {
layout : 'card',
cardSwitchAnimation: 'slide',
initComponent : function() {
this.dockedItems = this.buildDockedItems();
this.items = this.buildItemList();
MyApp.views.HomeScreenPanel.superclass.initComponent.call(this);
},
buildItemList : function(){
return [
new Ext.Panel({html:"hello"}),
new Ext.Panel({html:"world"}),
];
},
buildDockedItems : function(){
return [
this.buildTopDockToolbar(),
this.buildBottomDockToolbar(),
];
},
buildTopDockToolbar : function(){
return {
xtype : 'toolbar',
dock : 'top',
title : 'My first MVC app',
};
},
buildBottomDockToolbar : function(){
return this.NavigationToolbar();
},
NavigationToolbar : function(){
return{
xtype : 'toolbar',
dock : 'bottom',
defaults : {
handler : this.NavigationToolbarHandler,
controller: 'NavigationBarController'
},
items : [
{
text : 'hello',
action: 'hello'
},
{
text : 'world',
action : 'world'
}]
};
},
NavigationToolbarHandler : function(btn) {
var exerciseListPanel = this.items.items[0], // CODE ERRORS HERE!
workoutListPanel = this.items.items[1];
Ext.dispatch({
controller : btn.controller,
action : btn.action,
views : {
exerciseListPanel: exerciseListPanel,
workoutListPanel: workoutListPanel,
}
})
},
});
Ext.reg('HomeScreenPanel',MyApp.views.HomeScreenPanel);
Here is the code for the controller but I don't there is a problem here:
Ext.regController('NavigationBarController', {
world : function(dataObj) {
Ext.Msg.alert(
'world!',
'world button pressed from toolbar',
Ext.emptyFn
);
MyApp.views.HomeScreenPanel.setActiveItem(dataObj.views.worldPanel); // CORRECT SYNTAX????
},
hello : function(dataObj) {
Ext.Msg.alert(
'hello',
'hello button pressed',
Ext.emptyFn
);
MyApp.views.HomeScreenPanel.setActiveItem(dataObj.views.helloPanel); // CORRECT SYNTAX?????
}
});
It is probably just a scope issue. try:
exerciseListPanel = MyApp.views.HomeScreenPanel.items.items[0];
In this context this is probably the button.
Items is a MixedCollection so use the get function.
http://docs.sencha.com/touch/1-1/#!/api/Ext.util.MixedCollection
MyApp.views.HomeScreenPanel.items.get(0);
Bit late but for anyone else googling in the future ;)