PDA

View Full Version : Fit to parent



Condor
4 Mar 2008, 2:19 AM
The ExtJS layout system works perfectly as long as you are using an Ext.Viewport or render to an element with fixed height and width.

But what if you already have a complete page design and want to fit an Ext component inside a div with flexible height and/or width?

I've posted the solution several times before, but I realized it would be easier to make a plugin out of it:


Ext.namespace('Ext.ux');
/**
* @class Ext.ux.FitToParent
* @extends Object
* <p>Plugin for {@link Ext.BoxComponent BoxComponent} and descendants that adjusts the size of the component to fit inside a parent element</p>
* <p>The following example will adjust the size of the panel to fit inside the element with id="some-el":<pre><code>
var panel = new Ext.Panel({
title: 'Test',
renderTo: 'some-el',
plugins: ['fittoparent']
});</code></pre></p>
* <p>It is also possible to specify additional parameters:<pre><code>
var panel = new Ext.Panel({
title: 'Test',
renderTo: 'other-el',
autoHeight: true,
plugins: [
new Ext.ux.FitToParent({
parent: 'parent-el',
fitHeight: false,
offsets: [10, 0]
})
]
});</code></pre></p>
* <p>The element the component is rendered to needs to have <tt>style="overflow:hidden"</tt>, otherwise the component will only grow to fit the parent element, but it will never shrink.</p>
* <p>Note: This plugin should not be used when the parent element is the document body. In this case you should use a {@link Ext.Viewport Viewport} container.</p>
*/
Ext.ux.FitToParent = Ext.extend(Object, {
/**
* @cfg {HTMLElement/Ext.Element/String} parent The element to fit the component size to (defaults to the element the component is rendered to).
*/
/**
* @cfg {Boolean} fitWidth If the plugin should fit the width of the component to the parent element (default <tt>true</tt>).
*/
fitWidth: true,
/**
* @cfg {Boolean} fitHeight If the plugin should fit the height of the component to the parent element (default <tt>true</tt>).
*/
fitHeight: true,
/**
* @cfg {Boolean} offsets Decreases the final size with [width, height] (default <tt>[0, 0]</tt>).
*/
offsets: [0, 0],
/**
* @constructor
* @param {HTMLElement/Ext.Element/String/Object} config The parent element or configuration options.
* @ptype fittoparent
*/
constructor: function(config) {
config = config || {};
if(config.tagName || config.dom || Ext.isString(config)){
config = {parent: config};
}
Ext.apply(this, config);
},
init: function(c) {
this.component = c;
c.on('render', function(c) {
this.parent = Ext.get(this.parent || c.getPositionEl().dom.parentNode);
if(c.doLayout){
c.monitorResize = true;
c.doLayout = c.doLayout.createInterceptor(this.fitSize, this);
} else {
this.fitSize();
Ext.EventManager.onWindowResize(this.fitSize, this);
}
}, this, {single: true});
},
fitSize: function() {
var pos = this.component.getPosition(true),
size = this.parent.getViewSize();
this.component.setSize(
this.fitWidth ? size.width - pos[0] - this.offsets[0] : undefined,
this.fitHeight ? size.height - pos[1] - this.offsets[1] : undefined);
}
});
Ext.preg('fittoparent', Ext.ux.FitToParent);

The following example will adjust the size of the panel to fit inside the element with id="some-el":

var panel = new Ext.Panel({
title: 'Test',
renderTo: 'some-el',
plugins: ['fittoparent']
});
It is also possible to specify additional parameters:

var panel = new Ext.Panel({
title: 'Test',
renderTo: 'other-el',
autoHeight: true,
plugins: [
new Ext.ux.FitToParent({
parent: 'parent-el',
fitHeight: false,
offsets: [10, 0]
})
]
});
The element the component is rendered to needs to have style="overflow:hidden", otherwise the component will only grow to fit the parent element, but it will never shrink.

Note: This plugin should not be used when the parent element is the document body. In this case you should use an Ext.Viewport container.

mabello
4 Mar 2008, 4:20 AM
Good job Condor, thanks!

lamtung
4 Mar 2008, 7:36 AM
I've tried it but firefox said "Ext.ux.plugins has no properties" ?
P.S : I added your code in the beginning of my js file

galdaka
4 Mar 2008, 8:04 AM
Excellent idea!!


But not work for me. I have a gridpanel in a div and the gridpanel is not resize properly!


Thanks,

galdaka
4 Mar 2008, 8:05 AM
I've tried it but firefox said "Ext.ux.plugins has no properties" ?
P.S : I added your code in the beginning of my js file

Register namespace: Ext.namespace("Ext.ux.plugins");

galdaka
4 Mar 2008, 8:14 AM
Excellent idea!!


But not work for me. I have a gridpanel in a div and the gridpanel is not resize properly!


Thanks,

SOLVED!!: .parentNode.parentNode

Would be great define in a param the parent level you can adjust it!!!!

Thanks again

Condor
8 Mar 2008, 4:03 AM
I updated the original code to allow you to specify the parent element.

galdaka
9 Mar 2008, 8:32 AM
Excellent plugin!!!

galdaka
9 Mar 2008, 8:32 AM
Excellent plugin!!!

Thanks again!!

mbalusu
7 May 2008, 12:49 PM
Hi,
I tried using this plugin and was sort of successfull in having my grid resizing when the browser resizes, except :

Say the browser is in NON-maximized mode and then you try to maximize by hitting maximize button in the titile bar of the borwser (IE), there is a long delay before the my grid "wakes" up and shows itself resized. In the meantime IE is frozen as if it is in a tight loop and unable to refresh the UI. Then all of a sudden it wakes up and everything refreshes.

Anybody else seen this problem or is it just me? How do I fix this?

Thanks.

Condor
12 May 2008, 11:18 AM
You probably have a grid with a lot of rows and/or columns and set forceFit or autoResizeColumn.
Either don't use forceFit/autoResizeColumn or try to reduce the amount of rows by using a paging toolbar (or use the LiveGrid extension).

andrew.howard@gtri.gatech.edu
13 May 2008, 7:56 AM
The following html used in conjunction with this plugin can make many problems associated with embedding an Ext.Panel into a percentage width/height element (table/div/etc) go away:


<div style="position:relative; width: 100%; height: 100%;">
<div id="mainContainer"
style="overflow: hidden; position: absolute; width: 100%; height: 100%; top: 0; left: 0;"/>
</div>

galdaka
9 Jun 2008, 12:38 PM
I modify the plugin for configure the adjust manually in some cases:



Ext.namespace('Ext.ux.plugins');
Ext.ux.plugins.FitToParent = function(parent, width, height) {
return {
init: function(c) {
c.on('render', function(c) {
parent = Ext.get(parent || c.el.dom.parentNode);
});
c.monitorResize = true;
c.doLayout = c.doLayout.createInterceptor(function(){
var pos = this.getPosition(), size = parent.getViewSize();
var w = width || pos[0];
var h = height || pos[1];
this.setSize(size.width - w, size.height - h);
}, c);
c.on('resize', function(c){
c.doLayout();
});
}
}
}



Example of usage:



new Ext.ux.plugins.FitToParent(null, null, 48)


Greetings,

Condor
9 Jun 2008, 9:49 PM
I modify the plugin for configure the adjust manually in some cases:

Why did you add:


c.on('resize', function(c){
c.doLayout();
});

Setting c.monitorResize = true already makes Ext.Container call doLayout on resize, so in your code doLayout gets called twice!

galdaka
10 Jun 2008, 10:07 AM
Why did you add:


c.on('resize', function(c){
c.doLayout();
});

Setting c.monitorResize = true already makes Ext.Container call doLayout on resize, so in your code doLayout gets called twice!

If I remove this line not work properly in my case, When resize west panel in www.galdaka.es

Condor
10 Jun 2008, 11:34 AM
If I remove this line not work properly in my case, When resize west panel in www.galdaka.es

Ah... You're using the plugin in way I never planned for (fixing accordion layout issues).

In your case you shouldn't use the monitorResize:true, because this option is meant for standalone components, not components in a layout.

galdaka
10 Jun 2008, 12:04 PM
Thanks for your reply,

Another question. In west panel I have a "SeacrhField"; Is posible resize the field when the west panel is resized with your plugin?

Thanks in advance,

mysticav
13 Sep 2008, 5:46 PM
I was having problems. Passing the document body has the parent fixed it:


new Ext.Panel({
layout: 'border',
renderTo:'viewPort',
plugins: [new Ext.ux.plugins.FitToParent(Ext.getBody())], ...

nbourdeau
19 Nov 2008, 1:19 PM
I'm having problems trying to get this work.

I have a div with : width: 100%.
I renderTo the grid in.
But the grid gets a wrong width (getting out the screen !!!)

Can someone please give an example of the code and the html used to have a grid fit 100% width of a non-Extjs container ? (ex. a div)

Condor
19 Nov 2008, 10:39 PM
Did you set the div to overflow:hidden?

Suresh
25 Dec 2008, 8:54 PM
I have used this plug-in successfully, but while resizing the window height of the grid is reducing. Is there any problem with my code?




grid = new Ext.ux.AutoGridPanel({
//title:'Auto loading columnmodel',
renderTo: 'sampleGrid',
height:500,
loadMask: true,
store: store,
bbar: pagingBar,
plugins: [new Ext.ux.plugins.FitToParent('sampleGrid')],
footer: false,
shadow : true,
frame : true,
loadMask: true,
monitorResize:true
});
// render grid
grid.render();
// load + metadata
grid.store.load({params: {meta: true, start:0, limit:100}});




div tag is:

<div id="sampleGrid style="height:100%;width:100%;overflow:hidden"></div>


In IE 6 when I open the page the grid is reducing gradually and after that it not showing the grid data.

Thanks,
Suresh

Suresh
25 Dec 2008, 10:25 PM
Solved! I was wrong. I have to put the sampleGrid in gridParentDiv with height like below.


<div id="gridParentDiv" style="height:400px;">
<div id="sampleGrid" style="width:100%;overflow:hidden"></div>
</div>



plugins: [summary, new Ext.ux.plugins.FitToParent("gridParentDiv")],



Thanks,
Suresh

Animal
31 Mar 2009, 1:29 AM
I'm upgrading a legacy app to use Ext Components outside of a layout scheme.

I was finding that the getPosition call was returning the Component's absolute position, not its local position relative to its containing element which meant that the size would be set incorrectly. So I needed to change the code to be



Ext.namespace('Ext.ux.plugins');
Ext.ux.plugins.FitToParent = Ext.extend(Object, {
init: function(c) {
c.on('render', function(c) {
parent = Ext.get(parent || c.el.dom.parentNode);
});
c.monitorResize = true;
c.doLayout = c.doLayout.createInterceptor(function(){
var pos = this.getPosition(true), size = parent.getViewSize();
this.setSize(size.width - pos[0], size.height - pos[1]);
}, c);
}
});

Animal
31 Mar 2009, 5:10 AM
Also, generating a new function to use as the interceptor function's target function every time is not very efficient, so I used a member function, "fitSizeToParent".



Ext.namespace('Ext.ux.plugins');
Ext.ux.plugins.FitToParent = Ext.extend(Object, {
constructor: function(parent) {
this.parent = parent;
},

init: function(c) {
c.on('render', function(c) {
this.parent = Ext.get(this.parent || c.el.dom.parentNode);
});
c.monitorResize = true;
c.doLayout = c.doLayout.createInterceptor(this.fitSizeToParent);
},

fitSizeToParent: function() {
var pos = this.getPosition(true), size = this.parent.getViewSize();
this.setSize(size.width - pos[0], size.height - pos[1]);
}
});

Condor
31 Mar 2009, 6:28 AM
Also, generating a new function to use as the interceptor function's target function every time is not very efficient, so I used a member function, "fitSizeToParent".

Almost, but the parent isn't passed to the component:

Ext.namespace('Ext.ux.plugins');
Ext.ux.plugins.FitToParent = Ext.extend(Object, {
constructor: function(parent) {
this.parent = parent;
},
init: function(c) {
c.fitToParentEl = this.parent;
c.on('render', function(c) {
this.parent = Ext.get(this.fitToParentEl || c.el.dom.parentNode);
});
c.monitorResize = true;
c.doLayout = c.doLayout.createInterceptor(this.fitSizeToParent);
},
fitSizeToParent: function() {
var pos = this.getPosition(true), size = this.fitToParentEl.getViewSize();
this.setSize(size.width - pos[0], size.height - pos[1]);
}
});

ps.
1. I renamed 'parent' to 'fitToParentEl' to avoid property name conflicts.
2. In Ext 3.0 you should use this.getDomPositionEl() instead of this.el.

Animal
31 Mar 2009, 6:59 AM
Ah, well spotted. I'll fix that here, or course I forgot that the scope in that function will be the client Component, not the plugin.

I also always use {single: true} on a render listener to that the listener is removed as soon as it runs.

Animal
31 Mar 2009, 7:03 AM
So, the Ext 3.0 version:



Ext.namespace('Ext.ux.plugins');
Ext.ux.plugins.FitToParent = Ext.extend(Object, {
constructor: function(parent) {
this.parent = parent;
},

init: function(c) {
c.on('render', function(c) {
c.fitToElement = Ext.get(this.parent || c.getDomPositionEl().dom.parentNode);
}, {single: true});
c.monitorResize = true;
c.doLayout = c.doLayout.createInterceptor(this.fitSizeToParent);
},

fitSizeToParent: function() {
var pos = this.getPosition(true), size = this.fitToElement.getViewSize();
this.setSize(size.width - pos[0], size.height - pos[1]);
}
});

Condor
31 Mar 2009, 7:07 AM
Still wrong:

Ext.namespace('Ext.ux.plugins');
Ext.ux.plugins.FitToParent = Ext.extend(Object, {
constructor: function(parent) {
this.parent = parent;
},
init: function(c) {
c.on('render', function(c) {
c.fitToElement = Ext.get(this.parent || c.getDomPositionEl().dom.parentNode);
}, this, {single: true});
c.monitorResize = true;
c.doLayout = c.doLayout.createInterceptor(this.fitSizeToParent);
},
fitSizeToParent: function() {
var pos = this.getPosition(true), size = this.fitToElement.getViewSize();
this.setSize(size.width - pos[0], size.height - pos[1]);
}
});

Animal
31 Mar 2009, 7:12 AM
Ouch! yes, a missed arg there.

hash_man
1 Apr 2009, 1:15 AM
Hi,I alway find a way to fit the grid to the screen. I think you have made an excellent work.
But I can't use it. I put the plugin code at the begin of my js file. But the firebug report like below:

Ext.ux.plugins is undefined

How can I use it?

Thanks

Animal
1 Apr 2009, 3:21 AM
The Ext.namespace statement?

Animal
23 Apr 2009, 10:41 PM
A suggestion here.

How about adding a monitorWindowResize option so that it automatically refits the Component to its parent on window resize.

This would be useful for when the parent element is sized using %ages.

Then we could help this guy: http://extjs.com/forum/showthread.php?t=66606

Animal
23 Apr 2009, 10:48 PM
so



Ext.namespace('Ext.ux.plugins');
Ext.ux.plugins.FitToParent = Ext.extend(Object, {
constructor: function(parent, monitorWindowResize) {
this.parent = parent;
if (monitorWindowResize) {
Ext.EventManager.onWindowResize(this.fitSizeToParent, this);
}
},
init: function(c) {
c.on('render', function(c) {
c.fitToElement = Ext.get(this.parent || c.getDomPositionEl().dom.parentNode);
}, this, {single: true});
c.monitorResize = true;
c.doLayout = c.doLayout.createInterceptor(this.fitSizeToParent);
},
fitSizeToParent: function() {
var pos = this.getPosition(true), size = this.fitToElement.getViewSize();
this.setSize(size.width - pos[0], size.height - pos[1]);
}
});

Condor
24 Apr 2009, 1:13 AM
onWindowResize isn't required when the plugin is applied to a Container, but it is always required when the Component isn't a Container.

So I would suggest:

Ext.namespace('Ext.ux.plugins');
Ext.ux.plugins.FitToParent = Ext.extend(Object, {
constructor: function(parent) {
this.parent = parent;
},
init: function(c) {
c.on('render', function(c) {
c.fitToElement = Ext.get(this.parent || c.getDomPositionEl().dom.parentNode);
if(!c.doLayout){
this.fitSizeToParent();
Ext.EventManager.onWindowResize(this.fitSizeToParent, this);
}
}, this, {single: true});
if(c.doLayout){
c.monitorResize = true;
c.doLayout = c.doLayout.createInterceptor(this.fitSizeToParent);
}
},
fitSizeToParent: function() {
var pos = this.getPosition(true), size = this.fitToElement.getViewSize();
this.setSize(size.width - pos[0], size.height - pos[1]);
}
});
(you need to call fitSizeToParent and attach the onWindowResize after the component is rendered)

bjmiller
30 Apr 2009, 9:41 AM
So, what ended up being the final version of this plugin for 2.x? Lots of code snippets here.

Condor
30 Apr 2009, 11:22 AM
I've updated the first post with the last code (most changes were minor, so it didn't really matter which version you used).

bjmiller
30 Apr 2009, 12:12 PM
Thank you!

whdanj
22 May 2009, 10:24 AM
It is great to find this plug in, I am trying to use it.

In my application, I put a tabpanel into a div (fromContainer), I develop on 1280x1024 screen resolution, everything looks fine.

But users use 1024x768 resolution, then some content of my page (most right side, bottom page) got cut off, I can not see them.

I tried to use the plug in, but it's not working, only tabs displayed, the content of the tabs does not show at all. please help, thanks a lot!



My jsp file:


<div id="formContainer" style="width:100%; height:100%; overflow:hidden">
</div>

My tab panel:


// Here is the MAIN SOURCE TAB
var tabs = new Ext.TabPanel({
renderTo: document.getElementById("formContainer"),
activeTab: 1,
plugins: [new Ext.ux.plugins.FitToParent()],
layoutOnTabChange: true,
//layout:'fit',
items:
[
// Add Source Tab
{
title: 'Add Source',
bodyStyle:'text-align:left;',
cls: 'left-right-buttons',
frame:true,
items: [addSourceForm,addSourceResult]
},

// Search Source Tab
{
title: 'Search Source',
cls: 'left-right-buttons',
defaults:{autoScroll: true},
items:
[{items: new Ext.Panel
({
height:650,
width:1140,
layout:'border',
defaults: {
bodyStyle: 'padding:5px'
,labelStyle:'font-weight: bold'
,bodyStyle:"background-color:#DED8C7"
,autoScroll: true
},
items:[{
title:"<font size=2>Searching Options</font>",
region:"west",
width:300,
minSize:100,
maxSize:300,
collapsible:true,
margins: '5 0 0 5',
items: searchForm
},{
title: '<font size=2>Source Detail Viewer</font>',
collapsible: false,
region:'east',
margins: '5 0 0 0',
width: 280,
items: detailForm
},{
title: '<font size=2>Source List</font>',
collapsible: false,
region:'center',
margins: '5 0 0 0',
id: 'sourceViewer',
layout: 'fit',
autoScroll: true,
//width: 580,
//defaults:{autoWidth: true},
items: sourceGrid
}]
})
}]
},

// My sources Tab
{
title: 'My Sources',
cls: 'left-right-buttons',
defaults:{autoScroll: true},
items:
[{items: new Ext.Panel
({
height:650,
width:1140,
layout:'border',
defaults: {
//split: true,
bodyStyle: 'padding:5px'
,labelStyle:'font-weight: bold'
,bodyStyle:"background-color:#DED8C7"
,autoScroll: true
}
,items:[{
title: '<font size=2>Source Detail</font>',
collapsible: false,
region:'east',
id:'pendingSourceViewer',
//margins: '5 0 0 0',
width: 280,
items: mySourceDetailForm
},
{
title: '<font size=2>My Source List</font>',
collapsible: false,
region:'center',
//margins: '5 0 0 0',
id: 'allMySources',
layout: 'fit',
autoScroll: true,
//width: 580,
//defaults:{autoWidth: true},
items: mySourceGrid
}]
})
}]
}//end of my Source tab
]//end of tab items
}); //end of tab panel

Animal
22 May 2009, 10:59 AM
If you want to use the full browser window, use a Viewport.

whdanj
22 May 2009, 5:48 PM
If you want to use the full browser window, use a Viewport.

Thanks. I have not used Viewport before, could you please give more details?

My layout:


div (formContainer)
|
tabPanel
| | |
tab1 tab2 tab3
(form) (borderLayout in panel2) (borderLayout in panel3)so should I put my tabPanel into the viewport? or put panel2(panel3) into the ViewPort?

thanks a lot!

Animal
24 May 2009, 9:45 AM
It's up to you!

Read the docs, read the examples.

http://extjs.com/deploy/ext-3.0-rc1.1/docs/?class=Ext.Viewport

Not forgetting that inheritance diagram at the top right... Viewport is a Container, and the following tells you all you need to know: http://extjs.com/deploy/ext-3.0-rc1.1/docs/?class=Ext.Container

Tinki
3 Jun 2009, 3:36 AM
Thank you for the plugin - the thing I've been looking for!
:-? Just one thing, I need to set the <div> I use as container, like:


plugins: [new Ext.ux.plugins.FitToParent('targetDivId')]
Maybe include it to example - will save a minute of experiments :D

Tinki
8 Jun 2009, 5:12 AM
IE6. Press F11. One more time (exit fs mode).
Width dimension of the panel stacks at the value which was set for fs mode.:-?

Maxrunner
9 Jul 2009, 5:19 AM
This isnt working with ie8 for some reason...its working fine with all the other browsers....as usual.

Condor
9 Jul 2009, 5:42 AM
This isnt working with ie8 for some reason...its working fine with all the other browsers....as usual.

Are you sure the parent is changing size?

Can you post a simple example (HTML + javascript)?

Maxrunner
9 Jul 2009, 5:45 AM
Yes here it is:


Ext.namespace('Ext.ux.plugins');
Ext.ux.plugins.FitToParent = Ext.extend(Object, {
constructor: function(parent) {
this.parent = parent;
},
init: function(c) {
c.on('render', function(c) {
c.fitToElement = Ext.get(this.parent || c.getDomPositionEl().dom.parentNode);
if(!c.doLayout){
this.fitSizeToParent();
Ext.EventManager.onWindowResize(this.fitSizeToParent, this);
}
}, this, {single: true});
if(c.doLayout){
c.monitorResize = true;
c.doLayout = c.doLayout.createInterceptor(this.fitSizeToParent);
}
},
fitSizeToParent: function() {
var pos = this.getPosition(true), size = this.fitToElement.getViewSize();
this.setSize(size.width - pos[0], size.height - pos[1]);
}
});


Ext.onReady(function(){

// second tabs built from JS
var tabs2 = new Ext.TabPanel({
renderTo: 'tabPanelWrapper',
plugins: [new Ext.ux.plugins.FitToParent("tabPanelWrapper")],
activeTab: 0,
//autoHeight:true,
autoWidth:true,
plain:false,
defaults:{autoScroll: true},
items:[{
title: 'Requerente',
autoLoad: {url: 'displayconteudo.do2', params: 'tab=dadosRequerente&numero=${param['numero']}', scripts: true}
},{
title: 'Documentos Anexados',
autoLoad: {url: 'displayconteudo.do2', params: 'tab=listDocumentos&numero=${param['numero']}', scripts: true}
},{
title: 'Histórico do Processo',
autoLoad: {url: 'displayconteudo.do2', params: 'tab=historico&numero=${param['numero']}', scripts: true}
},{
title: 'Informações',
autoLoad: {url: 'displayconteudo.do2', params: 'tab=informacoes&numero=${param['numero']}', scripts: true}
},{
title: 'Etapas',
autoLoad: {url: 'displayconteudo.do2', params: 'tab=etapas&numero=${param['numero']}', scripts: true}
}
]
});



<div id="tabPanelWrapper" style='width: auto;overflow:hidden'></div>

zyon
15 Jul 2009, 2:50 AM
Hi
I am using this plugin,but it looks like i have to set a fixed height to the parent element in order to work.Is there a way to set a procentual height to parent too?


Html:


div id="center" style='height:1000px;'>
<div id="colorToolbar"></div>
<div id="companiesGrid" style='overflow:hidden;height:100%;width:100%'></div>


Viewport:



var viewport = new Ext.Viewport([

{
region: 'center',
xtype: 'panel',
contentEl: 'center',

}, {
id: 'companyDetailsRegion',
region: 'south',
title: 'Double click a company from the list above to see its details',
collapsible: true,
contentEl: 'south',
frame : true,
split: true,
collapsed: true,
}
]);
Grid:



var grid = new Ext.grid.GridPanel({
id: 'companiesGrid',
ds: ds,
cm: cm,
enableColLock: false,
loadMask: true,
view: new Ext.grid.GridView({
autoFill: true
}),
plugins: [filters, new Ext.ux.plugins.FitToParent()],
el: 'companiesGrid',
renderTo: 'companiesGrid',
autoExpandColumn:'CompanyName'
});


grid.render();

Maxrunner
15 Jul 2009, 2:52 AM
Ive just decided to use the defaults:{autoHeight:true}, it works with IE too.

aleksf
6 Nov 2009, 11:12 AM
I have a grid:

var grid = new Ext.grid.GridPanel({
width:'100%',
autoHeight: true,
title:'Beam Caster Heat List',
store: store,
trackMouseOver:false,
disableSelection:false,
loadMask: true,
border:false,
plugins: [new Ext.ux.plugins.FitToParent()],
cm: new Ext.grid.ColumnModel([
{header: "Col1", dataIndex: 'COL1', width: 60, sortable: true} // ... etc
]),
viewConfig: {
forceFit:true,
enableRowBody:false,
showPreview:false
},
bbar: toolBar
});
grid.render('list-grid');
// ...
<div id="list-grid" style="overflow: hidden; position: absolute; width: 100%; height: 100%; top: 0; left: 0;" />
The grid is part of a HTML page rendered in an iframe:


<iframe id="tabProd" class="x-hide-display" width="100%" height="100%"></iframe>When the window is resized by dragging the border, both iframe and grid resize to fit. The problem is that, when the window is maximized or de-maximized, the iframe resizes fine with the window , but the grid does not resize with the iframe. It looks like the event does not get triggered. I have tried with just layout: 'fit' for the grid (without the FitToParent plugin) , but with same result.

What am I missing here?

TIA

Alex

benmclendon
6 Nov 2009, 11:20 AM
I think it would work if you put the grid inside a border layout.

e.g.



var viewport = new Ext.Viewport({
layout : 'border',
items : [{
region : 'center',
border : false,
layout: 'fit',
items : grid
}]
});

aleksf
6 Nov 2009, 11:28 AM
I think it would work if you put the grid inside a border layout.
Thanks for help, but it does not work. As I said, it looks like the resize event is either not generated or happens so fast that it's not picked up.

I've noticed another thing: if I max/de-max window few times, it appears as if the events are "swapped" - i.e. when maximized, the grid resize to the de-maximized window size and vice-versa. It happens in both FF and IE. Funny indeed.

aleksf
6 Nov 2009, 11:56 AM
I've noticed another thing: if I max/de-max window few times, it appears as if the events are "swapped" - i.e. when maximized, the grid resize to the de-maximized window size and vice-versa. It happens in both FF and IE. Funny indeed.
This (http://www.yui-ext.com/forum/showthread.php?t=77150) post describes something similar. In my case, it seems that, at maximize time, the window still has previous size values. Then, when it is reduced, it gets the maximized sizes.

wp.joju
10 Nov 2009, 6:53 AM
this plugin is really useful but i also need the parent to adjust if the child's height is already over the parent's height... here is what i have..

panel with table layout... inside 1 column is a panel containing 2 labels, 1 of the label needs to be on top of the panel and the other is aligned to the bottom part,,, i was able to make my panel (which contains the 2 labels) adjust to the table column height by using this... now what i need is to be able to adjust the column height when the label's height is already over the column's height,,., please help

Condor
10 Nov 2009, 7:06 AM
That is really out of the scope of the plugin. You should write your own fitSizeToParent method that does the correct size based on your needs.

wp.joju
10 Nov 2009, 9:41 PM
ok i'll just adjust this plugin for the needed changes to adopt to the child component's height, just 1 thing though, why is it that whenever i resize the browser window, the component's height increases each time even though it is not really needed, if it remove c.monitorResize = true; then the height is not changing

col
27 Dec 2009, 4:11 PM
I tried to use an example from the first post
but get an error
c.getDomPositionEl is not a function
for this line



c.on('render', function(c) {
c.fitToElement = Ext.get(this.parent || c.getDomPositionEl().dom.parentNode);
if(!c.doLayout){


i used EXTJS [2.2.1 - 2.3.0]
Where can I get the plugin working code for my version EXTJS.

steffenk
21 Jan 2010, 2:39 AM
Hi Condor,

after update to ExtJS 3.1 i get error with the plugin, especially with "getDomPositionEl" (... is not a function)

Did something changed? Is something simular now integrated in core?

Any advice is welcome.

Condor
21 Jan 2010, 2:43 AM
In Ext 3.1 the getDomPositionEl method was removed, because it is now the same as the getPositionEl method.

So you only have to change:

getDomPositionEl -> getPositionEl

steffenk
21 Jan 2010, 3:09 AM
Hi Condor,

thx - the js error is gone but the plugin does not work anymore, i changed this line:

c.fitToElement = Ext.get(this.parent || c.getPositionEl.dom.parentNode);

Now the grid tbar and bbar are not rendered anymore and grid is sized to no height, so i guess the reference element is wrong now. Do you know what the problem is?

btw - why does core not add something like layout: 'fitToParent' :)

Condor
21 Jan 2010, 3:42 AM
You removed the brackets!


c.fitToElement = Ext.get(this.parent || c.getPositionEl().dom.parentNode);

steffenk
21 Jan 2010, 3:48 AM
true - my fault, sry.
Ok, grid is rendered ok now, but no resizing is done, same result as without the plugin. I try to debug and hopefully find the problem, thanks again.

steffenk
21 Jan 2010, 4:18 AM
with debugging it seems that all is ok, the sizes are calculated correct.
but this does nothing anymore:

this.setSize(size.width - pos[0], size.height - pos[1]);

In my case this is instance of Ext.grid.GridPanel, it seems that something prevents the panel from resizing. looks like changed behaviour of layout cause this.

Hm, clueless at the moment.

steffenk
23 Jan 2010, 6:18 AM
Hi Condor,

all is working again. I forgot to remove "autoHeight" property which leads to strange results. Maybe this should be mentioned not to use it.

westvovik
15 Mar 2010, 9:38 AM
Greetings to all, I use your plug-in, it perfectly works, but there was a problem if I need to break the screen into two columns and in each column to place the grid that it is impossible to stretch the grid by means of a plug-in how to be with it

Condor
15 Mar 2010, 11:06 AM
You don't need the plugin for that. You can just use a Viewport with a HBoxLayout.

westvovik
15 Mar 2010, 1:56 PM
I already have one viewport on page, and besides in its central part is located tabpanel with tabs to me it is necessary to place in one tab 2 columns and already into each column to insert grid
sorry for my english

Condor
15 Mar 2010, 11:32 PM
You never need this plugin if you are using an Ext.Viewport (unless you are using iframes).

Could you draw a picture of how your layout should look like

aladdinwang
8 May 2010, 11:16 PM
So, the Ext 3.0 version:



Ext.namespace('Ext.ux.plugins');
Ext.ux.plugins.FitToParent = Ext.extend(Object, {
constructor: function(parent) {
this.parent = parent;
},

init: function(c) {
c.on('render', function(c) {
c.fitToElement = Ext.get(this.parent || c.getDomPositionEl().dom.parentNode);
}, {single: true});
c.monitorResize = true;
c.doLayout = c.doLayout.createInterceptor(this.fitSizeToParent);
},

fitSizeToParent: function() {
var pos = this.getPosition(true), size = this.fitToElement.getViewSize();
this.setSize(size.width - pos[0], size.height - pos[1]);
}
});



Hi, where can i find 'getDomPositionEl' method in Ext js API? I can't find either 'getPositionEl' or 'getDomPositionEl' in ext js api for version 3.2.1.

But when I run this plugins, it worked for version 3.2.1...

songwei118
6 Jun 2010, 9:14 PM
Great Plugin,

but if the component is not in a layout and the parent is hidden at first, how to fire the resize event when the parent is displayed later

Condor
6 Jun 2010, 9:49 PM
Call fitSize() after making the parent visible.

songwei118
6 Jun 2010, 11:00 PM
Hi, Condor . Thanks for your replay ,
is there any simpler way , since i have a tab panel rendered with a group of contentEl , which are also the markup of the grids.
the grid was rendered before the tabpanel ,so it can serve as the contentEl of a tab.

Condor
6 Jun 2010, 11:46 PM
You should not be using FitToParent if the container is an Ext component! In that case Ext layouts work much better.

mohaaron
22 Jun 2010, 3:18 PM
I've been having this problem where I get a blank white screen with this one custom component and I've just figured out part of the problem.

This code returns 0 for height which is causing what looks like an empty screen.

size = this.parent.getViewSize(); In this code extdom.getViewHeight() returns 453 and d.clientHeight returns 0.

getViewSize : function(){
var doc = document,
d = this.dom,
extdom = Ext.lib.Dom,
isDoc = (d == doc || d == doc.body);
return { width : (isDoc ? extdom.getViewWidth() : d.clientWidth),
height : (isDoc ? extdom.getViewHeight() : d.clientHeight) };
},Now if the getViewSize method only returned the value 453 I wouldn't have this problem. I also don't know this code and how it works. I don't understand why the FitToParent plugin doesn't work for this one component. Can anyone tell me how I can get this to work?

Here is the code that makes up the one component that doesn't work and which does work for the individual sub components.



<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<link href="../Scripts/ext-3.0.0/resources/css/ext-all.css" rel="stylesheet" type="text/css" />
<script src="../Scripts/ext-3.0.0/adapter/ext/ext-base.js" type="text/javascript"></script>
<script src="../Scripts/ext-3.0.0/ext-all-debug.js" type="text/javascript"></script>
<script src="../Scripts/ext-3.0.0/Core.js" type="text/javascript"></script>
<script src="../Scripts/ext-3.0.0/Ext.form.EmployeeForm.js" type="text/javascript"></script>
<script src="../Scripts/ext-3.0.0/Ext.grid.EmployeeGrid.js" type="text/javascript"></script>
<script src="../Scripts/ext-3.0.0/Ext.grid.EmployeeSelectGrid.js" type="text/javascript"></script>
<script src="../Scripts/ext-3.0.0/Ext.grid.HardwareGrid.js" type="text/javascript"></script>
<script src="../Scripts/ext-3.0.0/Ext.grid.SoftwareGrid.js" type="text/javascript"></script>
<script src="../Scripts/ext-3.0.0/Ext.form.EquipmentEditor.js" type="text/javascript"></script>
<script src="../Scripts/ext.ux.ext-3.0.0/Ext.ux.grid.Search.js" type="text/javascript"></script>
<script src="../Scripts/ext.ux.ext-3.0.0/Ext.ux.override.Ext.form.ComboBox.js" type="text/javascript"></script>
<script src="../Scripts/ext.ux.ext-3.0.0/Ext.ux.form.ComboBox.Width.js" type="text/javascript"></script>
<script src="../Scripts/ext.ux.ext-3.0.0/Ext.ux.ComboLoader.js" type="text/javascript"></script>
<script src="../Scripts/ext.ux.ext-3.0.0/Ext.ux.FitToParent.js" type="text/javascript"></script>
<script type="text/javascript">
Ext.BLANK_IMAGE_URL = '../Scripts/ext-3.0.0/resources/images/default/s.gif';
Ext.onReady(function() {
Ext.QuickTips.init();

var equipmentEditor = new Ext.form.EquipmentEditor({
renderTo: 'formPanel',
basePath: '..',
plugins: [new Ext.ux.FitToParent()],
listeners: {
afterrender: function() {
// Get everything after the ? in the url.
var queryString = window.location.search.substring(1)
// Ext.urlDecode() returns an object like {key: value} which can be used like key.value
var user = Ext.urlDecode(queryString);
if (user.userid == null)
user.userid = 688;

this.loadForm(user.userid);
}
}
});
});
</script>
</head>
<body>

<div style="width:100%; height:100%; overflow:hidden" id="formPanel"></div>

</body>
</html>


Ext.form.EmployeeForm = Ext.extend(Ext.form.FormPanel, {
// Default config options.
id: 'employeeForm',
border: true,
frame: true,
labelWidth: 100,
buttonAlign: 'center',
basePath: '',

initComponent: function() {
this.hiddenId = new Ext.form.Hidden({
id: 'userId',
name: 'UserId',
value: 0
});

this.firstName = new Ext.form.TextField({
id: 'firstName',
name: 'FirstName',
fieldLabel: 'First Name',
allowBlank: false,
tabIndex: 1,
anchor:'98%'
});

this.lastName = new Ext.form.TextField({
id: 'lastName',
name: 'LastName',
fieldLabel: 'Last Name',
allowBlank: false,
tabIndex: 2,
anchor:'98%'
});

this.email = new Ext.form.TextField({
id: 'email',
name: 'Email',
fieldLabel: 'Email',
//allowBlank: false,
tabIndex: 3,
//vtype: 'email',
anchor:'98%'
});

this.networkId = new Ext.form.TextField({
id: 'networkId',
name: 'NetworkId',
fieldLabel: 'Network ID',
//allowBlank: false,
tabIndex: 4,
anchor:'98%'
});

this.networkOu = new Ext.form.TextField({
id: 'networkOu',
name: 'NetworkOu',
fieldLabel: 'Users OU',
//allowBlank: false,
tabIndex: 5,
anchor:'98%'
});

this.managerName = new Ext.form.TextField({
id: 'managerName',
name: 'ManagerName',
fieldLabel: 'Manager Name',
//allowBlank: false,
tabIndex: 6,
anchor:'98%'
});

this.managerEmail = new Ext.form.TextField({
id: 'managerEmail',
name: 'ManagerEmail',
fieldLabel: 'Manager Email',
//allowBlank: false,
tabIndex: 7,
anchor:'98%'
});

this.seniorManager = new Ext.form.TextField({
id: 'seniorManager',
name: 'SeniorManager',
fieldLabel: 'Senior Manager',
//allowBlank: false,
tabIndex: 8,
anchor:'98%'
});

this.address1 = new Ext.form.TextField({
id: 'address1',
name: 'Address1',
fieldLabel: 'Address',
//allowBlank: false,
tabIndex: 9,
anchor:'98%'
});

this.address2 = new Ext.form.TextField({
id: 'address2',
name: 'Address2',
fieldLabel: 'Address 2',
//allowBlank: false,
tabIndex: 10,
anchor:'98%'
});

this.city = new Ext.form.TextField({
id: 'city',
name: 'City',
fieldLabel: 'City',
//allowBlank: false,
tabIndex: 11,
anchor:'98%'
});

this.state = new Ext.form.ComboBox({
id: 'stateField',
name: 'State',
fieldLabel: 'State',
tabIndex: 12,
//width: 20,
anchor:'92%',
valueField: 'StateAbbrev', // Value passed in post to server.
displayField: 'StateAbbrev', // Display value from combo store field.
hiddenName: 'State', // This binds to data source and displays in combo display field.

// REMOTE MODE
// typeAhead: true,
// editable: true,
// minChars: 1,
// mode: 'remote',
// REMOTE MODE

// LOCAL MODE
typeAhead: true,
editable: true,
minChars: 1,
mode: 'local',
// LOCAL MODE

triggerAction: 'all', // Causes combo to query all data when the trigger action is fired.
forceSelection: true,
selectOnFocus: false,
//hideTrigger: true,
loadingText: 'Loading...',
store: new Ext.data.JsonStore({
id: 'StateId',
idProperty: 'StateId',
autoLoad: true,
root: 'data',
totalProperty: 'totalRows',
fields: ['StateId', 'StateName', 'StateAbbrev'],
proxy: new Ext.data.HttpProxy({ // or ScriptTagProxy for remote urls.
url: this.basePath + '/WebService.asmx/GetStates',
method: 'post',
headers: { 'Content-Type': 'application/json; charset=utf-8;' },
jsonData: {}
})
})
});

this.zipCode = new Ext.form.TextField({
id: 'zipCode',
name: 'ZipCode',
fieldLabel: 'Zip',
//allowBlank: false,
tabIndex: 12,
//width: 30,
anchor:'95%'
});

this.accountingUnit = new Ext.form.TextField({
id: 'accountingUnit',
name: 'AccountingUnit',
fieldLabel: 'AU',
//allowBlank: false,
tabIndex: 13,
//width: 30,
anchor:'98%'
});

// this.accountingUnit = new Ext.form.ComboBox({
// id: 'accountingUnit',
// name: 'AccountingUnit',
// fieldLabel: 'Accounting Unit',
// tabIndex: 11,
// anchor:'98%',
// valueField: 'AuNumber', // Value passed in post to server.
// displayField: 'AuNumber', // Display value from combo store field.
// hiddenName: 'AccountingUnit', // This binds to data source and displays in combo display field.
//
// // REMOTE MODE
//// typeAhead: true,
//// editable: true,
//// minChars: 1,
//// mode: 'remote',
// // REMOTE MODE
//
// // LOCAL MODE
// typeAhead: true,
// editable: true,
// minChars: 1,
// mode: 'local',
// // LOCAL MODE
//
// triggerAction: 'all', // Causes combo to query all data when the trigger action is fired.
// forceSelection: true,
// selectOnFocus: false,
// //hideTrigger: true,
// loadingText: 'Loading...',
// store: new Ext.data.JsonStore({
// id: 'AuNumber',
// idProperty: 'AuNumber',
// autoLoad: true,
// root: 'data',
// totalProperty: 'totalRows',
// fields: ['AuNumber'],
// proxy: new Ext.data.HttpProxy({ // or ScriptTagProxy for remote urls.
// url: this.basePath + '/WebService.asmx/GetAccountingUnits',
// method: 'post',
// headers: { 'Content-Type': 'application/json; charset=utf-8;' },
// jsonData: {}
// })
// })
// });

this.employmentType = new Ext.form.TextField({
id: 'employmentType',
name: 'EmploymentType',
fieldLabel: 'Employee Type',
//allowBlank: false,
tabIndex: 14,
anchor:'98%'
});

this.mac = new Ext.form.TextField({
id: 'mac',
name: 'Mac',
fieldLabel: 'Mac',
//allowBlank: false,
tabIndex: 15,
anchor:'98%'
});

this.cdrwRights = new Ext.form.TextField({
id: 'cdrwRights',
name: 'CdrwRights',
fieldLabel: 'Cdrw Rights',
style: { fontWeight: 'bold' },
width: 20,
tabIndex: 16,
//,anchor:'98%'
listeners: {
blur: function() {
var currentValue = this.getValue().toUpperCase();
this.setValue(currentValue);
}
}
});

this.usbRights = new Ext.form.TextField({
id: 'usbRights',
name: 'UsbRights',
fieldLabel: 'Usb Rights',
style: { fontWeight: 'bold' },
width: 20,
tabIndex: 17,
//,anchor:'98%'
listeners: {
blur: function() {
var currentValue = this.getValue().toUpperCase();
this.setValue(currentValue);
}
}
});

this.adminRights = new Ext.form.TextField({
id: 'adminRights',
name: 'AdminRights',
fieldLabel: 'Admin Rights',
style: { fontWeight: 'bold' },
width: 20,
tabIndex: 18,
//,anchor:'98%'
listeners: {
blur: function() {
var currentValue = this.getValue().toUpperCase();
this.setValue(currentValue);
}
}
});

/*
Date: 2010.01.20.1135
Name: Aaron Prohaska
Note: This is not used in the form yet.
*/
// this.remoteRights = new Ext.form.TextField({
// id: 'remoteRights',
// name: 'RemoteRights',
// fieldLabel: 'Remote Rights',
// style: { fontWeight: 'bold' },
// width: 20
// //,anchor:'98%'
// ,listeners: {
// blur: function() {
// var currentValue = this.getValue().toUpperCase();
// this.setValue(currentValue);
// }
// }
// });

this.rightsJustification = new Ext.form.TextField({
id: 'rightsJustification',
name: 'RightsJustification',
fieldLabel: 'Justification',
//allowBlank: false,
tabIndex: 19,
anchor:'98%'
});

this.validatedByInitials = new Ext.form.TextField({
id: 'validatedByInitials',
name: 'ValidatedByInitials',
fieldLabel: 'Validated By',
//allowBlank: false,
tabIndex: 20,
anchor:'98%'
//,width: 50
});

var config = {
monitorValid: true,
items: [
this.hiddenId,
{
layout: 'column',
items: [{
layout: 'form',
labelWidth: 90,
columnWidth: .5,
items: [
this.firstName,
this.email,
this.networkOu,
this.managerEmail
]
}, {
layout: 'form',
columnWidth: .5,
items: [
this.lastName,
this.networkId,
this.managerName,
this.seniorManager
]
}]
}, {
// START: COLUMN
layout: 'column',
items: [{
layout: 'form',
labelWidth: 90,
columnWidth: .5,
items: [
this.address1
]
}, {
layout: 'form',
//labelWidth: 22,
columnWidth: .5,
items: [
this.address2
]
}
// , {
// layout: 'form',
// labelWidth: 26,
// columnWidth: .25,
// items: [
// this.mac
// ]
// }
] // END: COLUMN
}, {
// START: COLUMN
layout: 'column',
items: [{
layout: 'form',
labelWidth: 90,
columnWidth: .5,
items: [
this.city
]
}, {
layout: 'form',
labelWidth: 35,
columnWidth: .11,
items: [
this.state
]
}, {
layout: 'form',
labelWidth: 20,
columnWidth: .13,
items: [
this.zipCode
]
}, {
layout: 'form',
labelWidth: 25,
columnWidth: .26,
items: [
this.accountingUnit
]
}] // END: COLUMN
}, {
layout: 'column',
items: [{
layout: 'form',
labelWidth: 90,
columnWidth: .5,
items: [
this.employmentType
]
}, {
layout: 'form',
columnWidth: .5,
items: [
this.mac
]
}]
}, {
// START: BOOLEAN FIELDS
layout: 'column',
items: [{
layout: 'form',
labelWidth: 76,
columnWidth: .25,
items: [this.cdrwRights]
}, {
layout: 'form',
labelWidth: 70,
columnWidth: .25,
items: [this.usbRights]
}, {
layout: 'form',
labelWidth: 80,
columnWidth: .5,
items: [this.adminRights]
}] // END: BOOLEAN FIELDS
}, {
// START: BOOLEAN FIELDS
layout: 'column',
items: [{
layout: 'form',
labelWidth: 76,
columnWidth: .84,
items: [this.rightsJustification]
}, {
layout: 'form',
labelWidth: 80,
columnWidth: .16,
items: [this.validatedByInitials]
}] // END: BOOLEAN FIELDS
}
// ,
// this.rightsJustification,
// this.validatedByInitials
]
};

// apply config
Ext.apply(this, Ext.apply(this.initialConfig, config));

Ext.form.EmployeeForm.superclass.initComponent.apply(this, arguments);
}

,onRender: function() {
Ext.form.EmployeeForm.superclass.onRender.apply(this, arguments);

// this.cdrwRights.el.setStyle('font-weight', 'bold');
// this.usbRights.el.setStyle('font-weight', 'bold');
// this.adminRights.el.setStyle('font-weight', 'bold');
}

,afterRender: function(grid) {
Ext.form.EmployeeForm.superclass.afterRender.apply(this, arguments);
}

,afterLayout: function() {
Ext.form.EmployeeForm.superclass.afterLayout.apply(this, arguments);
}
});
Ext.reg('employeeform', Ext.form.EmployeeForm);


Ext.grid.HardwareGrid = Ext.extend(Ext.grid.EditorGridPanel, {
// Default config options.
id: 'hardwareGrid',
basePath: '',
hideUserFields: true,
hideSaveButton: false,
hideDeleteButton: false,

initComponent: function() {
this.search = new Ext.ux.grid.Search({
iconCls:'icon-zoom'
,searchText: 'Search'
//,readonlyIndexes:['UserId']
//,disableIndexes:['pctChange']
,minChars:2
,autoFocus:true
,width: 130
})

this.sharedFieldData = [
['Y'],
['N'],
['?']
]

var config = {
//autoExpandColumn: 'notes',
border: true,
loadMask: {msg: 'Loading...'},
clicksToEdit: 'auto',
columnLines: true,
stripeRows: true,
view: new Ext.grid.GridView({
//forceFit: true,
getRowClass : function (record, index) {
var cls = '';
var data = record.data;

if (data.EndOfSupportDate !== '') {
var endOfSupport = data.EndOfSupportDate;
var today = new Date();
var addThreeMonths = new Date(new Date().setMonth(today.getMonth() + 3));

if (endOfSupport < today) {
cls = 'hardware-not-supported';
} else if (endOfSupport < addThreeMonths) {
cls = 'hardware-pending-support';
}
}

return cls;
}
}),
plugins: [
this.search,
new Ext.ux.ComboLoader()
],
tbar: [{
hidden: this.hideSaveButton,
text: 'Add',
handler: function(button) {
var hardwareStore = this.store;
var Hardware = hardwareStore.recordType;
var hardware = new Hardware();
this.stopEditing();
hardwareStore.insert(0, hardware);
this.startEditing(0, 5);
},
scope: this
}, {
text: 'Delete',
handler: function() {
Ext.Msg.show({
title: 'Confirm',
msg: 'Are you sure you want to delete this row?',
buttons: Ext.Msg.YESNO,
fn: function(button) {
if (button == 'yes') {
this.deleteHardware();
}
},
animEl: 'elId',
icon: Ext.MessageBox.QUESTION,
scope: this
});
},
scope: this
}, {
xtype: 'tbseparator'
}, {
text: 'Change Owner',
handler: function() {
Ext.Msg.show({
title: 'Confirm',
msg: 'Are you sure you want to change this hardware\'s owner?',
buttons: Ext.Msg.YESNO,
fn: function(button) {
if (button == 'yes') {
var path = this.basePath;
// Open window with search grid for employee selection.
var changeOwnerWin = new Ext.Window({
id: 'changeOwnerWin',
title: 'Employee Search',
layout: 'fit',
closeAction: 'hide',
plain:true,
width: 800,
height: 300,
items: [{
xtype: 'employeeselectgrid',
basePath: this.basePath,
bbar: [{
text: 'Confirm Change',
handler: function() {
// "this" should be the EmployeeSelectGrid.
this.changeOwner(Ext.getCmp('employeeSelectGrid'));
},
scope: this
}]
}]
}).show();
}
},
animEl: 'elId',
icon: Ext.MessageBox.QUESTION,
scope: this
});
},
scope: this
}, {
xtype: 'tbseparator'
}, {
text: 'Dispose',
handler: function() {
Ext.Msg.show({
title: 'Confirm',
msg: 'Are you sure you want to dispose of this hardware?',
buttons: Ext.Msg.YESNO,
fn: function(button) {
if (button == 'yes') {
this.disposeHardware();
}
},
animEl: 'elId',
icon: Ext.MessageBox.QUESTION,
scope: this
});
},
scope: this
}, {
xtype: 'tbfill'
}, {
text: 'Export To Excel',
handler: function() {
var fields = [];
this.search.menu.items.each(function(item) {
if (item.checked && item.dataIndex != undefined) {
fields.push(item.dataIndex);
}
});
var query = this.search.field.getValue();
var queryString = window.location.search.substring(1)
var query = Ext.urlDecode(queryString);
if (query.userid == null)
window.open('HardwareToExcel.aspx?fields=' + fields + '&query=' + query);
else
window.open('HardwareToExcel.aspx?userid=' + query.userid);
},
scope: this
}, {
xtype: 'tbtext',
id: 'rowCount',
text: 'Total: 0',
style: {
fontWeight: 'bold'
}
}],
bbar: [],
store: new Ext.data.JsonStore({
id: 'HardwareId',
idProperty: 'HardwareId',
root: 'data',
totalProperty: 'totalRows',
proxy: new Ext.data.HttpProxy({
url: this.basePath + '/WebService.asmx/GetHardware',
//proxy: new Ext.data.ScriptTagProxy({
//url: 'http://localhost:4557/CDG.Equipment.WebServices/WebService.asmx/GetHardware',
method: 'post',
headers: { 'Content-Type': 'application/json; charset=utf-8;' },
jsonData: {}
}),
fields: [
{name: 'HardwareId', type: 'int'},
{name: 'UserId', type: 'int'},
{name: 'LastName', type: 'string'},
{name: 'FirstName', type: 'string'},
{name: 'NetworkId', type: 'string'},
{name: 'Manager', type: 'string'},
{name: 'SeniorManager', type: 'string'},
{name: 'HardwareType', type: 'string'},
{name: 'Manufacturer', type: 'string'},
{name: 'Model', type: 'string'},
{name: 'HardwareName', type: 'string'},
{name: 'PartNumber', type: 'string'},
{name: 'PurchaseDate', type: 'date', dateFormat: 'm/d/Y'},
{name: 'EndOfSupportDate', type: 'date', dateFormat: 'm/d/Y'},
{name: 'Notes', type: 'string'},
{name: 'Shared', type: 'string'}
]
}),
columns: [{
hidden: true,
header: 'HardwareId',
dataIndex: 'HardwareId'
}, {
hidden: this.hideUserFields,
header: 'User Id',
dataIndex: 'UserId',
//displayIndex: 'UserId',
sortable: true,
width: 60,
renderer: function(value, metaData, record, rowIndex, colIndex, store) {
return '<a href="EquipmentEditor.aspx?userid=' + value + '" target="_blank">Edit (' + value + ')</a>';
}
}, {
hidden: this.hideUserFields,
header: 'Last Name',
dataIndex: 'LastName',
sortable: true,
width: 140
}, {
hidden: this.hideUserFields,
header: 'First Name',
dataIndex: 'FirstName',
sortable: true,
width: 120
}, {
hidden: this.hideUserFields,
header: 'Network ID',
dataIndex: 'NetworkId',
sortable: true,
width: 60
}, {
hidden: this.hideUserFields,
header: 'Manager Name',
dataIndex: 'Manager',
sortable: true,
width: 120
}, {
hidden: this.hideUserFields,
header: 'Senior Manager',
dataIndex: 'SeniorManager',
sortable: true,
width: 120
}, {
header: 'WF Computer Name',
dataIndex: 'HardwareName',
sortable: true,
width: 120,
editor: new Ext.form.TextField({
//
})
}, {
header: 'Make',
dataIndex: 'Manufacturer',
sortable: true,
width: 100,
editor: new Ext.form.TextField({
//
})
}, {
header: 'Model',
dataIndex: 'Model',
sortable: true,
width: 100,
editor: new Ext.form.TextField({
//
})
}, {
header: 'Serial Number',
dataIndex: 'PartNumber',
sortable: true,
width: 120,
editor: new Ext.form.TextField({
//
})
}, {
header: 'Hardware Type',
dataIndex: 'HardwareType',
sortable: true,
width: 90,
editor: new Ext.form.ComboBox({
id: 'hardwareTypeField',
name: 'HardwareType',
//fieldLabel: 'Hardware Type',
//tabIndex: 11,
//anchor:'98%',
valueField: 'HardwareTypeName', // Value passed in post to server.
displayField: 'HardwareTypeName', // Display value from combo store field.
hiddenName: 'HardwareTypeName', // This binds to data source and displays in combo display field.

// REMOTE MODE
// typeAhead: true,
// editable: true,
// minChars: 1,
// mode: 'remote',
// REMOTE MODE

// LOCAL MODE
typeAhead: true,
editable: true,
minChars: 1,
mode: 'local',
// LOCAL MODE

triggerAction: 'all', // Causes combo to query all data when the trigger action is fired.
forceSelection: true,
selectOnFocus: false,
//hideTrigger: true,
loadingText: 'Loading...',
store: new Ext.data.JsonStore({
id: 'HardwareTypeName',
idProperty: 'HardwareTypeName',
autoLoad: true,
root: 'data',
totalProperty: 'totalRows',
fields: ['HardwareTypeName'],
proxy: new Ext.data.HttpProxy({ // or ScriptTagProxy for remote urls.
url: this.basePath + '/WebService.asmx/GetHardwareTypes',
method: 'post',
headers: { 'Content-Type': 'application/json; charset=utf-8;' },
jsonData: {}
})
})
})
}, {
header: 'Shared',
dataIndex: 'Shared',
sortable: true,
width: 50,
editor: new Ext.form.ComboBox({
id: 'sharedCombo',
name: 'Shared',
//fieldLabel: 'Hardware Type',
//tabIndex: 11,
//anchor:'98%',
valueField: 'Shared', // Value passed in post to server.
displayField: 'Shared', // Display value from combo store field.
hiddenName: 'Shared', // This binds to data source and displays in combo display field.

// REMOTE MODE
// typeAhead: true,
// editable: true,
// minChars: 1,
// mode: 'remote',
// REMOTE MODE

// LOCAL MODE
typeAhead: true,
editable: true,
minChars: 1,
mode: 'local',
// LOCAL MODE

triggerAction: 'all', // Causes combo to query all data when the trigger action is fired.
forceSelection: true,
selectOnFocus: false,
//hideTrigger: true,
loadingText: 'Loading...',
store: new Ext.data.ArrayStore({
id: 'Shared',
fields: [{name: 'Shared', type: 'string'}],
data: this.sharedFieldData
})
})
// editor: new Ext.form.TextField({
// style: { fontWeight: 'bold' },
// autoCreate: {tag: 'input', type: 'text', size: '8', autocomplete: 'off', maxlength: '1'},
// listeners: {
// blur: function() {
// var currentValue = this.getValue().toUpperCase();
// this.gridEditor.record.set('Shared', currentValue);
// }
// }
// })
}, {
header: 'Purchase Date',
dataIndex: 'PurchaseDate',
sortable: true,
width: 85,
renderer: Ext.util.Format.dateRenderer('m/d/Y'),
editor: new Ext.form.DateField({
//
})
}, {
header: 'EOS Date',
dataIndex: 'EndOfSupportDate',
sortable: true,
width: 65,
renderer: Ext.util.Format.dateRenderer('m/d/Y'),
editor: new Ext.form.DateField({
//
})
// editor: new Ext.form.TextField({
// plugins: [
// new Ext.ux.InputTextMask(
// '99/99/9999',
// true // Clear field when value is invalid.
// )
// ]
// })
}, {
id: 'notes',
header: 'Notes',
dataIndex: 'Notes',
width: 600,
sortable: true,
editor: new Ext.form.TextField({
//
}),
renderer: function(value, metaData, record) {
metaData.attr = 'ext:qtip="' + record.data.Notes + '" ext:qtitle="Notes"';
return value;
}
}]
};

// apply config
Ext.apply(this, Ext.apply(this.initialConfig, config));

Ext.grid.HardwareGrid.superclass.initComponent.apply(this, arguments);

this.getStore().on('load', function(store, records, options) {
var rowCount = store.totalLength;
// TODO: How to get local tbar label?
Ext.getCmp('rowCount').setText('Total: ' + rowCount);
});
}

,onRender: function() {
Ext.grid.HardwareGrid.superclass.onRender.apply(this, arguments);
}

,afterRender: function(grid) {
Ext.grid.HardwareGrid.superclass.afterRender.apply(this, arguments);
}

,afterLayout: function() {
Ext.grid.HardwareGrid.superclass.afterLayout.apply(this, arguments);
}

,load: function(userId) {
// Force form 'post'.
var params = {
userId: userId
};
this.store.proxy.conn.jsonData = params;

this.store.load();
}

,isValid : function(){
var valid = true;
Ext.each(this.getStore().getModifiedRecords(), function(record) {
valid = record.isValid();
});
return valid;
}

,isDirty : function(){
var dirty = false;
Ext.each(this.getStore().getModifiedRecords(), function(record) {
dirty = record.dirty;
});
return dirty;
}

,deleteHardware: function() {
var cell = this.getSelectionModel().getSelectedCell();
if (cell) {
var record = this.store.getAt(cell[0]);
var hardwareId = record.id;

if (hardwareId && parseInt(hardwareId) > 0) {
Ext.Ajax.request({
url: this.basePath + '/WebService.asmx/DeleteHardware', // GetTestMethod
method: 'post',
headers: { 'Content-Type': 'application/json; charset=utf-8;' },
jsonData: { hardwareId: hardwareId },
success: function(form, action){
var response = Ext.util.JSON.decode(form.responseText);

if (response.success) {
// On success remove row.
this.store.remove(record);
//Ext.MessageBox.alert('Message', response.data);
} else {
Ext.MessageBox.alert('Message', response.data);
}
},
failure: function(form, action){
var response = Ext.util.JSON.decode(form.responseText);
Ext.MessageBox.alert('Message', response.data);
},
scope: this
});
} else {
// Remove unsaved row from grid.
this.store.remove(record);
}

this.getSelectionModel().select(0, 2);
}
}

,changeOwner: function(employeeSelectGrid) {
//var cell = this.getSelectionModel().getSelectedCell();
var selections = employeeSelectGrid.getSelectionModel().getSelections();
// The selection model is set internally to RowSelectionModel({singleSelect:true}) so there can only be one selection.
var employeeRecord = selections[0];
if (employeeRecord) {
var hardwareCell = this.getSelectionModel().getSelectedCell();
var hardwareRecord = this.store.getAt(hardwareCell[0]);
var hardwareId = hardwareRecord.data.HardwareId;
var newUserId = employeeRecord.data.UserId;

if ((hardwareId && parseInt(hardwareId) > 0) && (newUserId && parseInt(newUserId) > 0)) {
Ext.Ajax.request({
url: this.basePath + '/WebService.asmx/ChangeHardwareOwner', // GetTestMethod
method: 'post',
headers: { 'Content-Type': 'application/json; charset=utf-8;' },
jsonData: { hardwareId: hardwareId, newUserId: newUserId },
success: function(form, action){
var response = Ext.util.JSON.decode(form.responseText);

if (response.success) {
// On success remove row.
this.store.remove(hardwareRecord);
// Maybe we redirect to page showing employee/hardware that hardware was transferred to?
window.location.replace(this.basePath + '/EquipmentEditor.aspx?userid=' + newUserId);
//Ext.getCmp('changeOwnerWin').hide();
} else {
Ext.MessageBox.alert('Message', response.data);
}
},
failure: function(form, action){
var response = Ext.util.JSON.decode(form.responseText);
Ext.MessageBox.alert('Message', response.data);
},
scope: this
});
}
}
}

,disposeHardware: function() {
var cell = Ext.getCmp('hardwareGrid').getSelectionModel().getSelectedCell();
if (cell) {
var record = this.store.getAt(cell[0]);
var hardwareId = record.id;

if (hardwareId && parseInt(hardwareId) > 0) {
Ext.Ajax.request({
url: this.basePath + '/WebService.asmx/DisposeHardware', // GetTestMethod
method: 'post',
headers: { 'Content-Type': 'application/json; charset=utf-8;' },
jsonData: { hardwareId: hardwareId },
success: function(form, action){
var response = Ext.util.JSON.decode(form.responseText);

if (response.success) {
this.store.remove(record);
} else {
Ext.MessageBox.alert('Message', response.data);
}
},
failure: function(form, action){
var response = Ext.util.JSON.decode(form.responseText);
Ext.MessageBox.alert('Message', response.data);
},
scope: this
});
} else {
// Remove unsaved row from grid.
this.store.remove(record);
}

this.getSelectionModel().select(0, 2);
}
}
});
Ext.reg('hardwaregrid', Ext.grid.HardwareGrid);


Ext.form.EquipmentEditor = Ext.extend(Ext.Panel, {
// Default public config options.
id: 'equipmentEditor',
//title: 'Equipment Editor',
border: false,
frame: false,
// hardwareGridHeight: 100,
// softwareGridHeight: 100,
buttonAlign: 'left', // Temp IE fix for hidden panel bug (http://www.extjs.com/forum/showthread.php?t=79409).
basePath: '',

//currentHardwareId: -1,

initComponent: function() {
// For tracking the previously selected hardware grid row.
this.employeeId = -1;
this.lastHardwareRowIndex = -1;
this.currentHardwareId = -1,

this.employeeForm = new Ext.form.EmployeeForm({
title: 'Employee',
basePath: this.basePath,
monitorValid: true,
trackResetOnLoad: true
// ,buttons: [
// new Ext.Button({
// text: 'Save',
// formBind: true,
// tabIndex: 21,
// handler: function() {
// this.save();
// },
// scope: this
// })
// ]
});

this.hardwareGrid = new Ext.grid.HardwareGrid({
title: 'Hardware',
basePath: this.basePath,
border: true,
frame: false,
//height: this.hardwareGridHeight,
bbar: [{
text: 'Save Changes',
scope: this,
handler: function(button) {
this.save();
}
}]
});

// Temperarily hidden.
// this.softwareGrid = new Ext.grid.SoftwareGrid({
// title: 'Software',
// basePath: this.basePath,
// hidden: true,
// //hideMode: 'offsets',
// border: true,
// frame: false,
// height: this.softwareGridHeight,
// tbar: [{
// text: 'Add',
// scope: this,
// handler: function(button) {
// var softwareStore = this.softwareGrid.store;
// var Software = softwareStore.recordType;
// var software = new Software();
// this.softwareGrid.stopEditing();
// softwareStore.insert(0, software);
// this.softwareGrid.startEditing(0, 1);
// }
// }, {
// xtype: 'tbseparator'
// }, {
// text: 'Delete',
// handler: function() {
// Ext.Msg.show({
// title: 'Confirm',
// msg: 'Are you sure you want to delete this row?',
// buttons: Ext.Msg.YESNO,
// fn: function(button) {
// if (button == 'yes') {
// this.deleteSoftware();
// }
// },
// animEl: 'elId',
// icon: Ext.MessageBox.QUESTION,
// scope: this
// });
// },
// scope: this
// }],
// scope: this
// });

var config = {
items: [
this.employeeForm,
this.hardwareGrid
//,this.softwareGrid
]
};

// APPLY CONFIG
Ext.apply(this, Ext.apply(this.initialConfig, config));
Ext.form.EquipmentEditor.superclass.initComponent.apply(this, arguments);

/*
HardwareGrid.store.load
Select cell(0,0) on load.
*/
this.hardwareGrid.getStore().on('load', function(store, records, options) {
var recordCount = store.getTotalCount();
if (recordCount == 0)
return;

var preventViewNotify = false;
var preventFocus = true;
this.hardwareGrid.getSelectionModel().select(0, 0, preventViewNotify, preventFocus);
}, this);

/*
HardwareGrid.CellSelect:
When a grid cell changes selection test the row and see if it's a new row. If the row
has changed then fetch new software data for selected hardware row.
*/
this.hardwareGrid.getSelectionModel().on('cellselect', function(sm, rowIndex, colIndex) {
if (this.lastHardwareRowIndex == rowIndex)
return;

var hardwareRecord = this.hardwareGrid.getStore().getAt(rowIndex);

if (!hardwareRecord.data.HardwareId) hardwareRecord.data.HardwareId = 0;

this.currentHardwareId = hardwareRecord.data.HardwareId;
// if (this.softwareGrid.hidden == false)
// this.softwareGrid.load(this.currentHardwareId);

this.lastHardwareRowIndex = rowIndex;
}, this);

/*
HardwareGrid.store.load
Select cell(0,0) on load.
*/
// this.softwareGrid.getStore().on('load', function(store, records, options) {
// var recordCount = store.getTotalCount();
// if (recordCount == 0)
// return;
//
// var preventViewNotify = false;
// var preventFocus = true;
// this.softwareGrid.getSelectionModel().select(0, 0, preventViewNotify, preventFocus);
// }, this);
}

,onRender: function() {
Ext.form.EquipmentEditor.superclass.onRender.apply(this, arguments);

this.employeeForm.getForm().findField('firstName');
}

,afterRender: function(grid) {
Ext.form.EquipmentEditor.superclass.afterRender.apply(this, arguments);
}

,afterLayout: function() {
Ext.form.EquipmentEditor.superclass.afterLayout.apply(this, arguments);
}

,loadForm: function(userId) {
if (userId === undefined || parseInt(userId) <= 0)
return;

this.employeeId = userId;

Ext.Ajax.request({
url: this.basePath + '/WebService.asmx/GetEmployee',
method: 'post',
headers: { 'Content-Type': 'application/json; charset=utf-8;' },
jsonData: {userId:userId},
success: function(form, action){
var response = Ext.util.JSON.decode(form.responseText);

this.employeeForm.getForm().setValues(response.data);

// Set initial value by inserting record into combo store.
//this.employeeForm.getForm().findField('accountingUnit').setValue(response.data.AccountingUnit);

this.hardwareGrid.load(userId);

//Ext.MessageBox.alert('Message', response.data);
},
failure: function(form, action){
var response = Ext.util.JSON.decode(form.responseText);
Ext.MessageBox.alert('Message', response.data);
},
scope: this
});
}

// ,deleteSoftware: function() {
// var cell = this.softwareGrid.getSelectionModel().getSelectedCell();
// if (cell) {
// var record = this.softwareGrid.store.getAt(cell[0]);
// var softwareId = record.id;
//
// if (softwareId && parseInt(softwareId) > 0) {
// Ext.Ajax.request({
// url: this.basePath + '/WebService.asmx/DeleteSoftware', // GetTestMethod
// method: 'post',
// headers: { 'Content-Type': 'application/json; charset=utf-8;' },
// jsonData: { softwareId: softwareId },
// success: function(form, action){
// var response = Ext.util.JSON.decode(form.responseText);
//
// if (response.success) {
// // On success remove row.
// this.softwareGrid.store.remove(record);
// //Ext.MessageBox.alert('Message', response.data);
// } else {
// Ext.MessageBox.alert('Message', response.data);
// }
// },
// failure: function(form, action){
// var response = Ext.util.JSON.decode(form.responseText);
// Ext.MessageBox.alert('Message', response.data);
// },
// scope: this
// });
// } else {
// // Remove unsaved row from grid.
// this.softwareGrid.store.remove(record);
// }
//
// this.softwareGrid.getSelectionModel().select(0, 2);
// }
// }

,save: function() {
var equipmentEditor = Ext.getCmp('equipmentEditor');
var employeeForm = Ext.getCmp('employeeForm');
var hardwareGrid = Ext.getCmp('hardwareGrid');
var hardwareStore = hardwareGrid.getStore();
// var softwareGrid = Ext.getCmp('softwareGrid');
// var softwareStore = softwareGrid.getStore();
var dataValidated = false;

// Convert data to json.
var formJson = Ext.util.JSON.encode(employeeForm.getForm().getValues());

// var hardwareJson = {};
// hardwareJson.HardwareId = equipmentEditor.currentHardwareId;
var hardwareRecords = hardwareStore.getModifiedRecords();
var hardwareJson = Ext.util.convertRecordsToJson(hardwareRecords);

// var softwareRecords = softwareStore.getModifiedRecords();
// var softwareParams = {HardwareRowIndex: equipmentEditor.lastHardwareRowIndex, HardwareId: equipmentEditor.currentHardwareId};
// var softwareJson = Ext.util.convertRecordsToJson(softwareRecords, softwareParams);
var softwareJson = {};

var dataIsDirty = (
employeeForm.getForm().isDirty() ||
hardwareGrid.isDirty()
// ||
// softwareGrid.isDirty()
)

var dataIsValid = (
employeeForm.getForm().isValid() ||
hardwareGrid.isValid()
// ||
// softwareGrid.isValid()
)

if (dataIsDirty && dataIsValid) {
Ext.Ajax.request({
url: this.basePath + '/WebService.asmx/SaveEquipmentEditor', // GetTestMethod
method: 'post',
headers: { 'Content-Type': 'application/json; charset=utf-8;' },
jsonData: { formData: formJson, hardwareData: hardwareJson, softwareData: softwareJson },
success: function(form, action){
var response = Ext.util.JSON.decode(form.responseText);

if (response.success) {
if (hardwareGrid.isDirty()) {
hardwareStore.commitChanges();
hardwareStore.reload();
}
//if (softwareGrid.isDirty()) {
//softwareStore.commitChanges();
//softwareStore.reload();
//softwareGrid.load(response.hardwareId);
//}

Ext.MessageBox.alert('Message', response.data);
}
else {
Ext.MessageBox.alert('Message', response.data);
}
},
failure: function(form, action){
var response = Ext.util.JSON.decode(form.responseText);
Ext.MessageBox.alert('Message', response.data);
}
});
} else {
if (!dataIsValid)
// TODO: Change this to list each of the invalid fields.
Ext.MessageBox.alert('Message', 'Data is not valid. Please check that you have entered all required fields.');
else if (!dataIsDirty)
Ext.MessageBox.alert('Message', 'No data has been changed.');
}
}
});
Ext.reg('equipmenteditor', Ext.form.EquipmentEditor);

Condor
22 Jun 2010, 10:36 PM
You want a full-screen application and you are not using an Ext.Viewport? Why?

If you want to get the same result as an Ext.Viewport then you should use:

html, body {
margin: 0;
padding: 0;
border: 0 none;
overflow: hidden;
height: 100%;
}

mohaaron
23 Jun 2010, 9:37 AM
Condor, thank you for the reply. I should have been a bit more clear. I'm do not want the same effect as a ViewPort. The example I'm showing doesn't contain the rest of the html that I have on the actual page I'm trying to make work so it just looks like I'm trying to do a full screen application. My end result page will have other html in it.

So I still need to figure out why the page I have gives me a 0 height. I'll go ahead and add some of the additional html which is supposed to be on the page and post a more complete example for you.

Condor
23 Jun 2010, 11:21 PM
If you want a full-screen application then you should still use an Ext.Viewport and use 'contentEl' or 'el' to move existing HTML inside the layout.

mohaaron
25 Jun 2010, 1:26 PM
Condor,

I'm still have the same problem here. I do not want to use a Viewport which is why I'm using your plugin. What I want is to figure out why my EmployeeForm and HardwareGrid work individually with your plugin but my EquipmentEditor does not. Your plugin does exactly what I want so I just have to figure out why the EquipmentEditor, which is a panel that contains the other two components, does not work. Do you have any idea why?

Thanks

acidtonic
27 Sep 2010, 9:36 AM
One small issue I had which might not matter for most, is that this plugin does not have an event for the scrollbar appearing.

If you have page that doesnt scroll, then suddenly some ajax event loads content which no longer fits in the page without a scrollbar, the page will change size if you aren't using overflow-y: hidden on the body element. If you then resize the browser window back to the same size it just was with the scroll bar still showing, the plugin kicks in and the layout is corrected. To me that indicates the scrollbar event should count towards forcing a refresh in the plugin. Since it breaks when the scroll shows, then corrects when you change the window size. The plugin should also resize when the scrollbar is shown.

In my case i dont want to do that and I instead forced the scrollbar to be visible even when not needed. I used the below snippet of css.

:root { overflow-y:scroll; }

thiner
13 Oct 2010, 5:15 AM
Hi guys,
Is there an available version for version 2.x?

Condor
13 Oct 2010, 5:20 AM
Is there an available version for version 2.x?

Haven't tested, but this plugin should probably also work on Ext 2.x (except Ext.preg - you always have to second method to specify the plugin).

thiner
13 Oct 2010, 6:11 AM
Haven't tested, but this plugin should probably also work on Ext 2.x (except Ext.preg - you always have to second method to specify the plugin).

No, at least Ext.isString is not work.
Anyway, I'm doing the adjusting work, will feed back to here when it's done.
Thank you.

thiner
13 Oct 2010, 6:41 AM
I got a really strange issue.
In IE6, my grid disappeared, just a div frame there.
What's wrong here?:-?



var filters = new Ext.ux.grid.GridFilters({
filters: [
{type: 'list', dataIndex: 'status', options: statuses},
{type: 'list', dataIndex: 'active', options: actives},
{type: 'list', dataIndex: 'ctrCprt', options: ctrCprts}
],
local: true
});

var fitToParent = new Ext.ux.FitToParent({
parent: 'divVtns',
fitHeight: false
});

var grid = new Ext.grid.GridPanel({
id: 'gridVtns'
,renderTo: 'divVtns'
,store: ds
,cm: cm
,stripeRows: true
,plugins: [filters, fitToParent]
,loadMask: true
//,bodyStyle:'width:100%'
,enableDragDrop: false
,viewConfig: {
forceFit:true
}
,border:false
//,autoHeight: true
,autoWidth: true
});




<tr>
<td style="overflow: hidden;">
<div id="divVtns" style="overflow: hidden;"></div>
</td>
</tr>

Condor
13 Oct 2010, 6:51 AM
1. A grid needs a height or autoHeight:true to display (FitToParent could also do this if you specify a parent with actual height).
2. You shouldn't use autoWidth:true now FitToParent is responsible for the width.

thiner
13 Oct 2010, 7:28 AM
1. A grid needs a height or autoHeight:true to display (FitToParent could also do this if you specify a parent with actual height).
2. You shouldn't use autoWidth:true now FitToParent is responsible for the width.

I tried your suggestions, but the grid still hidden.
Seems the plugin has recalculate the size of panel, but grid render failed.

Entire code:


<html>
<body>
<div>
<table width="100%" border="0" cellpadding="0" cellspacing="0"
class="blueBorder1px tableActive">
<tr>
<td height="25" style="width: 100%" align="left" valign="middle"
class="tableHeader noBorder">VTNs</td>
</tr>
<tr>
<td style="overflow: hidden;">
<div id="divVtns" style="overflow: hidden; height:500px;"></div>
</td>
</tr>
</table>

</div>

</BODY>
</HTML>


Ext.onReady(function(){
var ds = new Ext.data.JsonStore({
root: 'vtns',
//autoLoad: false,
fields: [{
name: 'name', mapping: 'name'
},{
name: 'num', mapping: 'fmiId'
},{
name: 'active', mapping: 'mbrActv'
},{
name: 'status', mapping: 'status'
},{
name: 'type', mapping: 'type'
},{
name: 'country', mapping: 'country'
},{
name: 'dateCreated', mapping: 'dateCreated', type:'date', dateFormat:'m/d/Y'
},{
name: 'ctrCprt',mapping:'ctrCprt'
}],
data: Ext.decode(vtnsJson)
});

var cm = new Ext.grid.ColumnModel(
[
{dataIndex: 'country', header: 'Country', renderer: renderSet, sortable: true},
{dataIndex: 'name', header: 'Name', renderer: renderLink,sortable: true},
{dataIndex: 'num', header: 'Number', sortable: true},
{dataIndex: 'active', header: 'Active' ,sortable: true},
{dataIndex: 'status', header: 'Status', sortable: true},
{dataIndex: 'type', header: 'VTN Type', renderer: renderSet},
{dataIndex: 'dateCreated', header: 'Date Created', renderer: Ext.util.Format.dateRenderer('m/d/Y'),sortable: true},
{dataIndex: 'ctrCprt', header: 'Central Counterparty',sortable: true}
]
);

function renderLink(value, meta, record, rIdx, cIdx, s){
var fmiId = record.get('num');
return '#';
}

function renderActive(isActive) {
return isActive ? 'Yes' : 'No';
}

function renderSet(value) {
return value.replace(/,/g,'<br>');
}


function renderCtrCprt(isCtrCprt) {
return isCtrCprt ? 'Yes' : 'No';
}

var filters = new Ext.ux.grid.GridFilters({
filters: [
{type: 'list', dataIndex: 'status', options: statuses},
{type: 'list', dataIndex: 'active', options: actives},
{type: 'list', dataIndex: 'ctrCprt', options: ctrCprts}
],
local: true
});

var fitToParent = new Ext.ux.FitToParent({
parent: 'divVtns'
//fitHeight: false
});

var grid = new Ext.grid.GridPanel({
id: 'gridVtns'
,renderTo: 'divVtns'
,store: ds
,cm: cm
,stripeRows: true
,plugins: [filters, fitToParent]
,loadMask: true
,bodyStyle:'width:100%'
,enableDragDrop: false
,viewConfig: {
forceFit:true
}
,border:false
,autoHeight: true
//,autoWidth: true
});
grid.show();
});

Condor
13 Oct 2010, 7:31 AM
1. The <td> should not be overflow:hidden.
2. Remove bodyStyle:'width:100%' and autoHeight:true (FitToParent is now handling both width and height).
3. Why are you not using an Ext.Viewport?

thiner
13 Oct 2010, 7:51 AM
1. The <td> should not be overflow:hidden.
2. Remove bodyStyle:'width:100%' and autoHeight:true (FitToParent is now handling both width and height).
3. Why are you not using an Ext.Viewport?

In fact, after add the actual height of div, it works. Sorry for posted a wrong thread. I looked at a previous page.(:|
But it introduce a new issue. The width of grid panel will fit to new frame width after maximize the frame. But fail to reduce the width of grid when the width of frame reduced.
The reason I don't use viewport is the grid is a component embed in a frame with other components.

Condor
13 Oct 2010, 8:02 AM
The reason I don't use viewport is the grid is a component embed in a frame with other components.

I would still recommend using a Viewport with a vbox layout that not only holds the grid, but also the other components.

rmatakajr
25 Oct 2010, 6:31 PM
You are the MAN!! you saved my ass ;)

altmisdort
30 Oct 2010, 6:12 AM
Did you guys check this plugin with ExtJS 3.3 and IE 8?
It seems to work with 3.1 and 3.2 just fine; but with 3.3, the content won't resize until the browser (IE 8) is resized.

Zeebee
5 Nov 2010, 2:21 AM
GREAT extension, this one saved me so much time :) A big thank you Condor ;)

steffenk
5 Nov 2010, 4:16 AM
Condor - wasn't there any feedback from sencha team to implement this? Or is the interest low because of Ext4?

Condor
5 Nov 2010, 4:27 AM
I haven't heard anything, but I'll ask them again at the conference.

rnegraobr
7 Nov 2010, 8:12 AM
Hi all,

I'm using se follow version of FitToParent :


Ext.namespace('Ext.ux');
/**
* @class Ext.ux.FitToParent
* @extends Object
* <p>Plugin for {@link Ext.BoxComponent BoxComponent} and descendants that adjusts the size of the component to fit inside a parent element</p>
* <p>The following example will adjust the size of the panel to fit inside the element with id="some-el":<pre><code>
var panel = new Ext.Panel({
title: 'Test',
renderTo: 'some-el',
plugins: ['fittoparent']
});</code></pre></p>
* <p>It is also possible to specify additional parameters:<pre><code>
var panel = new Ext.Panel({
title: 'Test',
renderTo: 'other-el',
autoHeight: true,
plugins: [
new Ext.ux.FitToParent({
parent: 'parent-el',
fitHeight: false,
offsets: [10, 0]
})
]
});</code></pre></p>
* <p>The element the component is rendered to needs to have <tt>style="overflow:hidden"</tt>, otherwise the component will only grow to fit the parent element, but it will never shrink.</p>
* <p>Note: This plugin should not be used when the parent element is the document body. In this case you should use a {@link Ext.Viewport Viewport} container.</p>
*/
Ext.ux.FitToParent = Ext.extend(Object, {
/**
* @cfg {HTMLElement/Ext.Element/String} parent The element to fit the component size to (defaults to the element the component is rendered to).
*/
/**
* @cfg {Boolean} fitWidth If the plugin should fit the width of the component to the parent element (default <tt>true</tt>).
*/
fitWidth: true,
/**
* @cfg {Boolean} fitHeight If the plugin should fit the height of the component to the parent element (default <tt>true</tt>).
*/
fitHeight: true,
/**
* @cfg {Boolean} offsets Decreases the final size with [width, height] (default <tt>[0, 0]</tt>).
*/
offsets: [0, 0],
/**
* @constructor
* @param {HTMLElement/Ext.Element/String/Object} config The parent element or configuration options.
* @ptype fittoparent
*/
constructor: function(config) {
config = config || {};
if(config.tagName || config.dom || Ext.isString(config)){
config = {parent: config};
}
Ext.apply(this, config);
},
init: function(c) {
this.component = c;
c.on('render', function(c) {
this.parent = Ext.get(this.parent || c.getPositionEl().dom.parentNode);
if(c.doLayout){
c.monitorResize = true;
c.doLayout = c.doLayout.createInterceptor(this.fitSize, this);
} else {
this.fitSize();
Ext.EventManager.onWindowResize(this.fitSize, this);
}
}, this, {single: true});
},
fitSize: function() {
var pos = this.component.getPosition(true),
size = this.parent.getViewSize();
this.component.setSize(
this.fitWidth ? size.width - pos[0] - this.offsets[0] : undefined,
this.fitHeight ? size.height - pos[1] - this.offsets[1] : undefined);
// this.component.doLayout();
}
});

Ext.preg('fittoparent', Ext.ux.FitToParent);


And i call plug-in how is follow:


var painelITENS = new Ext.Panel({
id : 'xpainelITENS',
plugins: [
new Ext.ux.FitToParent({
parent: 'FormTabPanel',
fitHeight: true,
fitWidht: true,
offsets: [ 20 , 215 + 10 ]
})
],
autoScroll : false,
frame : true,
renderTo : 'ListadeItens'
});

.....

var gridITENS = new Ext.grid.GridPanel({
id: 'xgridITENS',
store: WEBui.storeITENS,
loadMask: true,
stripeRows: true,
sm: new Ext.grid.RowSelectionModel({singleSelect:true}),
height: 200,
width : 400,
plugins: [
new Ext.ux.FitToParent({
parent: 'xpainelITENS',
fitHeight: true,
fitWidht: true,
offsets: [ 10 , 10 ]
})
],
stateful: true,
stateId: 'grid',
columns: [ ......

....

Ext.getCmp('xpainelITENS').add(gridITENS);
Ext.getCmp('xpainelITENS').doLayout();

....



My problem is : When i resize the west panel or browser window, the fitSize function runs before the central panel occurs completely. The result is the size of "last" panel size. I think that i need some "wait resource" or "before resizing" to implement on FitToParent, but I don't know how to do it.

NOTE : When i change the tab and back, i'm calling doLayout() and the size is corrected. It makes me think that i really need some "wait resource" or "before resizing".



var FormTabPanel = new Ext.TabPanel({
activeTab : 0,
deferredRender : false, // need this if you are going to include a form in your tab panel
id: 'FormTabPanel',
frame: true,
border: false,
anchor: '100%',
defaults : {
autoScroll : true,
bodyStyle : 'padding:10px'
},
items: [{
id: 'NFresumo',
height: altura[3]-127,
title : 'Informações Gerais',
contentEl : 'FormTab1'
},{
id: 'NFdetalhe',
title : 'Itens da Nota Fiscal',
contentEl : 'FormTab2'
}],
listeners: {
tabchange: function(tabp,tab){
if (tab.id=='NFdetalhe'){ Ext.getCmp('xpainelITENS').doLayout();};
}
}
});


Thanks for all.


23172
23173
23174

bbellmyers
17 Nov 2010, 12:46 PM
So, the Box Component is built of divs, right? Aren't divs 100% wide by default anyway? Why do we need all this code to set inline style widths, when "width: auto" would work as well? Is this for reverse compatibility with IE 6 or something?

Condor
17 Nov 2010, 2:50 PM
But all this is inside a tabpanel! You shouldn't be using FitToParent inside an Ext.Container.

Instead you should add the elements as boxcomponent items to the container. To get the proper width you could use layout:'anchor' on the container and anchor:'100%' on the boxcomponents.

rnegraobr
20 Nov 2010, 5:58 PM
I'm using Ext.ND and my TabPanel is inside of Ext.Nd.UIDocument.

I don't know why, but when i render de grid directly on the DIV, the behavior in IE is different of the Firefox. Sometimes the scroll bar appears in browser windows and sometimes the scroll bar in the grid doesn't (i need to click on the grid to show scroll bar).

My interesting is in height size because the panel above the grid will changed deppending of situation.

Using the FitToParent was the only way to have the same behavior in all browsers (IE, FF, Opera and Safari), including correct showing of scroll bar.

But using FitToParent, the function runs before the resize occurs, changing the size to the "last size".

So, how i put a "wait resource" to runs FitToParent only after resize occurrs ?

(sorry about my poor english)

Thanks in advance.

Condor
21 Nov 2010, 3:54 AM
I repeat: If this is in an Ext container (e.g. TabPanel) then you should not be rendering anything. You should add() the grid to the tabpanel and call doLayout().

rnegraobr
21 Nov 2010, 7:18 PM
Condor,
I'm not rendering (my mistake writing) I'm using add() and doLayout() to show the grid. But I'm doing it inside the ext.panel not directly on the TabPanel.

I'll try to add directly on TabPanel how you said.

Condor
22 Nov 2010, 12:26 AM
You can do it in a normal panel too, but you have to check 2 things:
1. Do you really need the panel (don't forget that a gridpanel is also a panel!).
2. Do all containers have a layout (e.g. is the panel layout:'fit')?

Zaphod Beeblebrox
5 Jan 2011, 12:24 PM
Condor, first, thank you.

I'm only a week or so into Ext JS and this plugin has given me great insight into Ext JS internals.

I'm working on a project that requires a border layout within a parent div. There's an additional UI that surrounds my app, and I'd like to keep that intact and not have to resort to Ext.Viewport and a separate pop-up.

I've got your plugin working somewhat - width resizing great, height, well not so much.

I've taken the complex layout sample code from the Sencha demo and placed it in a panel with your plugin defined. But the only way I can get anything more than a thin blue bar to appear is to give the panel a height:

After your Ext.ux is defined and inside an Ext.onReady I start with...


var panel = new Ext.Panel({
autoHeight: true,
// height: 600,
layout: 'border',
renderTo: 'content',
plugins: ['fittoparent'],
items: [ ...
The HTML wrapper looks like this...



<div style="border: 1px solid #f00;">
<div id="content" style="width: 100%; height: 100%; padding: 0; margin:0 overflow: hidden; min-height:500px;">
{pg->output_section f='layout'}
</div>
</div>
Smarty renders the HTML from the Sencha complex layout sample in response to the {pg->output_section f='layout'} call. The result can be seen in screen-shot-1.png below.

24118

The red border is to show me where the inner container "content" is showing as it shapes itself to the inner div. The thin blue line just below the top red line is the complex layout.

If I change the panel config (as follows) removing autoHeight and setting a height I get what's seen in screen-shot-2.png



var panel = new Ext.Panel({
// autoHeight: true,
height: 600,
layout: 'border',
renderTo: 'content',
plugins: ['fittoparent'],
items: [
24120

So, I have the UI rendering now, and changing the width tracks nicely. However, when I reduce the height of the browser I would expect to see a browser based scrollbar - but I get none... see screen-shot-3.png - sigh...

24119

What I'm shooting for is a minimum height presentation, a container div that expands to fit the contents of the border-layout, and browser scroll bars if the window is smaller than the rendered content.

What am I missing?

Condor
6 Jan 2011, 5:08 AM
The content div might be height:100%, but that doesn't work correctly in some browsers.

You should make both the HTML and BODY tags height:100% and use the body for the FitToParent 'parent' config option (optionally specify offsets to leave room for a footer).

scaddenp
1 Feb 2011, 3:02 PM
I'm beginner at this and it is not working as I expect. I have markup of:

<body style="height:100%">

<div id="hdr" style="position:relative;; z-index:2;">
<table width="100%" border="0" cellspacing="0" cellpadding="0" height="127">
<tr>
<td width="91%" height="100" background="images/HEADER.gif" background-repeat="no-repeat"><p class="pageName" align="center"> <font color="#ffffff">My Title, New Zealand</font></p></td>
<td height="100" width="9%"><div align="center"> <img src="images/GNS_new.gif" width="60" height="100" align="center" /></div></td>
</tr>
</table>
</div>
<div id= "AllContents" style=" width:100%; height:100%">
<div id= "MapFrame" frameborder="no" scrolling="no" style="overflow:hidden; width:100%; height:100%">
</div>
</div></body>and within a included js have:

mapPanel = new GeoExt.MapPanel({
title: "GeoExt MapPanel",
renderTo: "MapFrame",
stateId: "MapFrame",
map: map,
autoHeight:true,
bodyBorder:false,
border:false,
header:false,
zoom:5,
collapsible: false,
plugins: ['fittoparent'],
tbar: mapTBar
// getState and applyState are overloaded so panel size
// can be stored and restored
});
Now what I had hoped is that the mapframe div would be expanded to fill viewport and that fittoparent will fit mapPanel into it. If I specify a height for mapPanel, all is well. However, without a height, the clientHeight returned by getViewSize is just the height of tbar.

Have I can an issue with fittoparent, or with my html? Thanks.

Condor
2 Feb 2011, 12:21 AM
Not only the <body>, but also the <html> needs to be height:100%.

But you're probably better off using an Ext.Viewport anyway.

scaddenp
2 Feb 2011, 12:37 PM
Interesting. If I make that change, then viewport size increases but the setsize seems to be ignored. If I remove autoHeight:true from the panel, then wow, suddenly its there. However, the size is wrong. The parent div (mapFrame) appears to be set to the same size as the whole viewport, pos and offsets are zero. I wondered if this was due to position relative but removing position attributes makes no difference. The size of the divs earlier in the flow is being ignored.

I am reluctant to use Ext.Viewport. I am trying to make a js to include into many pieces of existing marking. I would prefer the js requires no knowledge of the markup it is being embedded into aside the name of div to use. As far as I can see from examples, using Ext.viewport would require me to boxcomponent the divs in the existing markup.

mvbaffa
14 Mar 2011, 11:42 AM
Hi,

I have a Viewport and in the central panel two DIVS and I would like to use your plugin. With so many replies I am lost.

Condor, would you please reply with the last version of the plugin. I am working with 3.3 version.

Thanks in advance.

motofix
22 Mar 2011, 6:33 AM
I'm definitivaly not a javascript nor ExtJS expert, but I think it may be usefull to share the modification I made to the plugin in order to make it work in my case, and using ExtJS 3.2.1

I'm generating a grid in an existing div using the 'applyTo' attribute. The issue I got with the plugin is the parent node width calculation, mainly with InternetExplorer, (<troll>this crappy browser ;-p</troll>). It was always for too large width, and resizing-down never worked.

Therefore, I modified the plugin to get the width of the parent at init time. I also take the size of the body as upper limit. Of course the following code can be simplified.


Ext.namespace('Ext.ux');
/**
* @class Ext.ux.FitToParent
* @extends Object
* <p>Plugin for {@link Ext.BoxComponent BoxComponent} and descendants that adjusts the size of the component to fit inside a parent element</p>
* <p>The following example will adjust the size of the panel to fit inside the element with id="some-el":<pre><code>
var panel = new Ext.Panel({
title: 'Test',
renderTo: 'some-el',
plugins: ['fittoparent']
});</code></pre></p>
* <p>It is also possible to specify additional parameters:<pre><code>
var panel = new Ext.Panel({
title: 'Test',
renderTo: 'other-el',
autoHeight: true,
plugins: [
new Ext.ux.FitToParent({
parent: 'parent-el',
fitHeight: false,
offsets: [10, 0]
})
]
});</code></pre></p>
* <p>The element the component is rendered to needs to have <tt>style="overflow:hidden"</tt>, otherwise the component will only grow to fit the parent element, but it will never shrink.</p>
* <p>Note: This plugin should not be used when the parent element is the document body. In this case you should use a {@link Ext.Viewport Viewport} container.</p>
*/
Ext.ux.FitToParent = Ext.extend(Object, {
/**
* @cfg {HTMLElement/Ext.Element/String} parent The element to fit the component size to (defaults to the element the component is rendered to).
*/
/**
* @cfg {Boolean} fitWidth If the plugin should fit the width of the component to the parent element (default <tt>true</tt>).
*/
fitWidth: true,
/**
* @cfg {Boolean} fitHeight If the plugin should fit the height of the component to the parent element (default <tt>true</tt>).
*/
fitHeight: true,
/**
* @cfg {Boolean} offsets Decreases the final size with [width, height] (default <tt>[0, 0]</tt>).
*/
offsets: [0, 0],
/**
* @constructor
* @param {HTMLElement/Ext.Element/String/Object} config The parent element or configuration options.
* @ptype fittoparent
*/
constructor: function(config) {
config = config || {};
if(config.tagName || config.dom || Ext.isString(config)){
config = {parent: config};
}
Ext.apply(this, config);
},
init: function(c) {
this.component = c;
this.maxWidth = Ext.get(document.body).getWidth(true)-12;
this.originalSize = Ext.get(c.initialConfig.applyTo).getWidth(true);
c.on('render', function(c) {
this.parent = Ext.get(this.parent || c.getPositionEl().dom.parentNode.parentNode);
if(c.doLayout){
c.monitorResize = true;
c.doLayout = c.doLayout.createInterceptor(this.fitSize, this);
} else {
this.fitSize();
Ext.EventManager.onWindowResize(this.fitSize, this);
}
}, this, {single: true});
},
fitSize: function() {
var pos = this.component.getPosition(true),
size = this.parent.getViewSize();
this.component.setSize(
this.fitWidth ? Math.min(this.maxWidth, Math.min(this.originalSize, size.width)) - pos[0] - this.offsets[0] : undefined,
this.fitHeight ? size.height - pos[1] - this.offsets[1] : undefined);
}
});
Ext.preg('fittoparent', Ext.ux.FitToParent);

erdeisz
27 May 2011, 5:13 AM
What about Ext JS 4?
FitToParent doesn't work for me with Ext JS 4.

justusvm
6 Jun 2011, 7:18 AM
Please post the same thing using extjs 4.0

foxmarco
8 Jun 2011, 1:18 AM
Please post the same thing using extjs 4.0

i also need the same thing!!! plz post solution for ext4

wawrek
8 Jun 2011, 4:14 AM
yes , it would be great to have the same plugin for ext4

piyuaryan
8 Jun 2011, 5:20 AM
I have saved your plugin code as Js file And i have included into my .html File.

Im getting this error when i load page.

"Ext.preg is not a function"
for
Ext.preg('fittoparent', Ext.ux.FitToParent);

foxmarco
29 Jun 2011, 1:49 AM
Anyone are planing a migration to extjs4?

westvovik
29 Jun 2011, 4:41 AM
Generally that not on a topic subject, I will be as soon as I will complete the large-scale project on extjs 3 then it is necessary to pass to 4 version gradually to rewrite all units

aggie
28 Jul 2011, 3:38 AM
Asking same question as Formarco.Any plans for having this in ext4?

KimSchneider
1 Sep 2011, 11:56 PM
/** * @class Ext.ux.FitToParent
* @extends Object
* <p>Plugin for {@link Ext.BoxComponent BoxComponent} and descendants that adjusts the size of the component to fit inside a parent element</p>
* <p>The following example will adjust the size of the panel to fit inside the element with id="some-el":<pre><code>
var panel = new Ext.Panel({
title: 'Test',
renderTo: 'some-el',
plugins: ['fittoparent']
});</code></pre></p>
* <p>It is also possible to specify additional parameters:<pre><code>
var panel = new Ext.Panel({
title: 'Test',
renderTo: 'other-el',
autoHeight: true,
plugins: [
new Ext.ux.FitToParent({
parent: 'parent-el',
fitHeight: false,
offsets: [10, 0]
})
]
});</code></pre></p>
* <p>The element the component is rendered to needs to have <tt>style="overflow:hidden"</tt>, otherwise the component will only grow to fit the parent element, but it will never shrink.</p>
* <p>Note: This plugin should not be used when the parent element is the document body. In this case you should use a {@link Ext.Viewport Viewport} container.</p>
*/
Ext.define('ux.FitToParent', {
extend : 'Ext.AbstractPlugin',


/**
* @cfg {HTMLElement/Ext.Element/String} parent The element to fit the component size to (defaults to the element the component is rendered to).
*/
/**
* @cfg {Boolean} fitWidth If the plugin should fit the width of the component to the parent element (default <tt>true</tt>).
*/
fitWidth: true,
/**
* @cfg {Boolean} fitHeight If the plugin should fit the height of the component to the parent element (default <tt>true</tt>).
*/
fitHeight: true,
/**
* @cfg {Boolean} offsets Decreases the final size with [width, height] (default <tt>[0, 0]</tt>).
*/
offsets: [0, 0],
/**
* @constructor
* @param {HTMLElement/Ext.Element/String/Object} config The parent element or configuration options.
* @ptype fittoparent
*/
constructor: function(config) {
config = config || {};
if(config.tagName || config.dom || Ext.isString(config)){
config = {parent: config};
}


this.callParent([config])
},
init: function(c) {
this.component = c;
c.on('render', function(c) {
this.parent = Ext.get(this.parent || c.getPositionEl().dom.parentNode);
if(c.doLayout){
c.monitorResize = true;
c.doLayout = c.doLayout.createInterceptor(this.fitSize, this);
} else {
this.fitSize();
Ext.EventManager.onWindowResize(this.fitSize, this);
}
}, this, {single: true});
},
fitSize: function() {
var pos = this.component.getPosition(true),
size = this.parent.getViewSize();


this.component.setSize(
this.fitWidth ? size.width - pos[0] - this.offsets[0] : undefined,
this.fitHeight ? size.height - pos[1] - this.offsets[1] : undefined);
}
});

Well, it's not that hard ;)

renganathan
27 Nov 2011, 5:11 AM
Hi condor,

Is "Fit to Parent" plugin is available in Extjs 4 ?

jgmeredith
9 Dec 2011, 1:34 PM
I get the following error when using extjs 4.0.7 on line 65 of the FitToParent class. I am attempting to use the code from post #115. If someone has a working example of this plugin for extjs 4 please share.


Uncaught TypeError: Object function () {
var me = this,
layout = me.getLayout();


if (me.rendered && layout && !me.suspendLayout) {

if (!me.isFixedWidth() || !me.isFixedHeight()) {

if (me.componentLayout.layoutBusy !== true) {
me.doComponentLayout();
if (me.componentLayout.layoutCancelled === true) {
layout.layout();
}
}
}

else {

if (layout.layoutBusy !== true) {
layout.layout();
}
}
}


return me;
} has no method 'createInterceptor'


line 65 of the FitToParent is


c.doLayout = c.doLayout.createInterceptor(this.fitSize, this);

My entry script looks like this


Ext.application({
name: 'ABC',
appFolder: 'app',


requires: [
'ABC.view.MainViewer',
'ABC.view.SummaryViewer',
'ABC.view.Menu',
'ABC.ux.FitToParent',
],


launch: function() {
Ext.create('Ext.panel.Panel', {
renderTo: 'content',
layout:'border',
plugins: ['fittoparent'],
items: [{
region: 'north',
xtype: 'menu'
}, {
region: 'center',
xtype: 'mainviewer'
}, {
region: 'west',
xtype: 'summaryviewer',
width: 300,
}]
});
}
});


My index.html page looks like this


<html><head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title id="page-title"></title>
<link rel="stylesheet" type="text/css" href="../extjs/resources/css/ext-all.css">
<script type="text/javascript" src="../extjs/ext-all-debug.js"></script>
<script type="text/javascript" src="app.js"></script>
<style>
a {color: white;}
.header {
padding: 20px; background: black; color: white;
}
</style>
</head>
<body>
<div id="header" class="header"><a href="/assets/ptr/index.html">Portal Navigation Bar Here</div>
<div id="content"></div>
</body>
</html>

vamsinarendera
13 Dec 2011, 8:30 PM
Hi jgmeredith (http://www.sencha.com/forum/member.php?204875-jgmeredith),
I am aslo getting the same error , and could not find any solution to fix it.iif u found som,e solution could u please help me in fixing it.

Thank You,
Vamsi Narender

enotha
13 Dec 2011, 11:35 PM
Hi

Im using fittoparent in extjs3.4. It works fine in firefox, but in IE8, when i resize the browser i get error

"Ext.fly(..)null or not an object."
It occurs at
if(!c.rendered){ c.render('x-form-el-' + c.id);
}else if(!this.isValidParent(c, target)){
// if(Ext.get(c.id)!=null)//added by enotha to fit to browser on window resize
Ext.fly('x-form-el-' + c.id).appendChild(c.getPositionEl());
}

this point where the Ext.get(c.id) is null. When i add the line if(Ext.get(c.id)!=null) it works perfectly in IE.but it is not good to add condition in ext-all-debug. how can i solve it?

var panel = new Ext.Panel({
autoScroll:true,
autoHeight:true,
id:'detailPanel',
header:false,
defaults: {
collapsible: false
},
plugins: [new Ext.ux.FitToParent("detailDiv")]
});


panel.add({
layout: 'column',
border:false,
items: [{
columnWidth: .19,
items:[grid]
},
{ columnWidth: .81 ,
items:loadCenterDetails("Planning")}
]
});

panel.render('detailDiv');

and in jsp <div id="detailDiv" style="width:100%;height:100%;overflow: hidden;">
</div>

thanks.

viran
30 Jan 2012, 9:32 PM
Good job Condor, Thanks!

AlphaBravo
27 Mar 2012, 5:33 AM
Has anyone found the fix for comment #115 as stated in comment #117?

won.rhee
4 Apr 2012, 4:20 PM
Has anyone found the fix for comment #115 as stated in comment #117?

+1 for this

JoelB
14 May 2012, 11:52 PM
+1 for this too

But why on earth cant we set 100% width on a panel ??? To always have to set the pixel width on resize sounds so ... heavy.

//J

yvkumar87
27 Sep 2012, 8:50 AM
Hi I have seen ur post i am not able to fix this issue with this below code
will u help me in this to resolve my issue I am new to ExtJs what changes i have to do in this below code
I am expecting the output like which is in attachment "output.png"
http://www.sencha.com/forum/showthread.php?243966-Help-Required&p=892521#post892521



The ExtJS layout system works perfectly as long as you are using an Ext.Viewport or render to an element with fixed height and width.

But what if you already have a complete page design and want to fit an Ext component inside a div with flexible height and/or width?

I've posted the solution several times before, but I realized it would be easier to make a plugin out of it:


Ext.namespace('Ext.ux');
/**
* @class Ext.ux.FitToParent
* @extends Object
* <p>Plugin for {@link Ext.BoxComponent BoxComponent} and descendants that adjusts the size of the component to fit inside a parent element</p>
* <p>The following example will adjust the size of the panel to fit inside the element with id="some-el":<pre><code>
var panel = new Ext.Panel({
title: 'Test',
renderTo: 'some-el',
plugins: ['fittoparent']
});</code></pre></p>
* <p>It is also possible to specify additional parameters:<pre><code>
var panel = new Ext.Panel({
title: 'Test',
renderTo: 'other-el',
autoHeight: true,
plugins: [
new Ext.ux.FitToParent({
parent: 'parent-el',
fitHeight: false,
offsets: [10, 0]
})
]
});</code></pre></p>
* <p>The element the component is rendered to needs to have <tt>style="overflow:hidden"</tt>, otherwise the component will only grow to fit the parent element, but it will never shrink.</p>
* <p>Note: This plugin should not be used when the parent element is the document body. In this case you should use a {@link Ext.Viewport Viewport} container.</p>
*/
Ext.ux.FitToParent = Ext.extend(Object, {
/**
* @cfg {HTMLElement/Ext.Element/String} parent The element to fit the component size to (defaults to the element the component is rendered to).
*/
/**
* @cfg {Boolean} fitWidth If the plugin should fit the width of the component to the parent element (default <tt>true</tt>).
*/
fitWidth: true,
/**
* @cfg {Boolean} fitHeight If the plugin should fit the height of the component to the parent element (default <tt>true</tt>).
*/
fitHeight: true,
/**
* @cfg {Boolean} offsets Decreases the final size with [width, height] (default <tt>[0, 0]</tt>).
*/
offsets: [0, 0],
/**
* @constructor
* @param {HTMLElement/Ext.Element/String/Object} config The parent element or configuration options.
* @ptype fittoparent
*/
constructor: function(config) {
config = config || {};
if(config.tagName || config.dom || Ext.isString(config)){
config = {parent: config};
}
Ext.apply(this, config);
},
init: function(c) {
this.component = c;
c.on('render', function(c) {
this.parent = Ext.get(this.parent || c.getPositionEl().dom.parentNode);
if(c.doLayout){
c.monitorResize = true;
c.doLayout = c.doLayout.createInterceptor(this.fitSize, this);
} else {
this.fitSize();
Ext.EventManager.onWindowResize(this.fitSize, this);
}
}, this, {single: true});
},
fitSize: function() {
var pos = this.component.getPosition(true),
size = this.parent.getViewSize();
this.component.setSize(
this.fitWidth ? size.width - pos[0] - this.offsets[0] : undefined,
this.fitHeight ? size.height - pos[1] - this.offsets[1] : undefined);
}
});
Ext.preg('fittoparent', Ext.ux.FitToParent);

The following example will adjust the size of the panel to fit inside the element with id="some-el":

var panel = new Ext.Panel({
title: 'Test',
renderTo: 'some-el',
plugins: ['fittoparent']
});
It is also possible to specify additional parameters:

var panel = new Ext.Panel({
title: 'Test',
renderTo: 'other-el',
autoHeight: true,
plugins: [
new Ext.ux.FitToParent({
parent: 'parent-el',
fitHeight: false,
offsets: [10, 0]
})
]
});
The element the component is rendered to needs to have style="overflow:hidden", otherwise the component will only grow to fit the parent element, but it will never shrink.

Note: This plugin should not be used when the parent element is the document body. In this case you should use an Ext.Viewport container.

brunp
3 Jan 2014, 1:47 PM
I am using Sencha Architect and not sure where to add the plugin. I am trying to auto-size a calendar pro module inside my container, which itself is inside a tab panel. The creation of the calendar module requires a fixed width/height to display properly, but I want it to auto-size to the parent's view port setting.

Any idea's?

Paul