Learning Ext JS 3

Toolbar in panels and windows Más videos

Descripción del tema

The panel component has the ability to add a toolbar functionality, in today's tutorial we're going to learn how we can do that and how we can use the buttons and menus of ExtJS.

Resources

Before you start this tutorial, you need to download the resources, unzip the file and copy the content to the folder "panels" we created at the beginning of this chapter, you can find this folder inside of a folder called "course" in the Web server we have installed in the first chapter. The resources for this tutorial are a HTML document that imports the ExtJS Framework and has some CSS classes and an empty JS file, inside of this file we're going to write the code for this tutorial, also we have another folder with the icons we're going to use for the toolbar. The example we're going to do today is a simulation of a Web browser, we'll use a toolbar for the buttons needed, an iFrame to display the pages we're specifying in the toolbar. So let's get started!

ExtJS 3.0

From this chapter and on we're going to use the version 3.0 of the ExtJS Framework, so if you don't have it please download it and copy it to the Web server inside of the folder "course".

Packaging the tutorial

Don't forget to package the code of this tutorial, to avoid future problems.
//the namespace for this tutorial
Ext.ns('com.quizzpot.tutorial');

//the blank image
Ext.BLANK_IMAGE_URL = '../ext-3.0.0/resources/images/default/s.gif';

com.quizzpot.tutorial.ToolbarTutorial = {
	init: function(){
		//code goes here
	}
}

Ext.onReady(com.quizzpot.tutorial.ToolbarTutorial.init,com.quizzpot.tutorial.ToolbarTutorial);

Toolbar

Let's create a window that contains a toolbar at the upper part of the screen like this:
this.win = new Ext.Window({
	title: 'Quizzpot Explorer',
	width: 600,
	height:450,
	tbar: [  // <--- ToolBar
		{text:'Back'}, // <--- Buttons
		{text:'Forward'},
		{text:'Reload'},
		{text:'Stop'},
		{text:'Home'}
	],
	maximizable: true,
	maskDisabled: true,
	bodyStyle: 'background-color:#fff',
	html: '<iframe id="container" src="http://www.google.com" style="width:100%;height:100%;border:none"></iframe>'
});
		
this.win.show();
The previous code creates a window with an iFrame where we display the Google's website, also it has some other properties we have studied in previous tutorials so I'm not going to explain them in detail at this moment, in this tutorial I want to talk about the property "tbar" which is the one responsible to assign a toolbar to the panel (remember that "Window" inherits properties from "Panel").
Basic Toolbar

Basic Toolbar

The property "tbar" accepts an array of buttons, a configuration object for the component "Ext.Toolbar" or an instance of the component "Ext.Toolbar", therefore we can create the window a little bit different:
this.win = new Ext.Window({
	title: 'Quizzpot Explorer',
	width: 600,
	height:450,
	tbar: {
		items: [
			{text:'Back'},
			{text:'Forward'},
			{text:'Reload'},
			{text:'Stop'},
			{text:'Home'}
		]
	},
	maximizable: true,
	maskDisabled: true,
	bodyStyle: 'background-color:#fff',
	html: '<iframe id="container" src="http://www.google.com" style="width:100%;height:100%;border:none"></iframe>'
});
		
this.win.show();
In the previous code the property "tbar" receives a configuration object for the component "Ext.Toolbar", this is very useful when we need to use the property "defaults", we can also use all the properties of the component (Toolbar). Now I'm going to show you how the property "tbar" accepts an instance of the component Toolbar:
//creates the tool bar
var toolbar = new Ext.Toolbar({
	items: [
		{text:'Back'},
		{text:'Forward'},
		{text:'Reload'},
		{text:'Stop'},
		{text:'Home'}
	]
});
		
this.win = new Ext.Window({
	title: 'Quizzpot Explorer',
	width: 600,
	height:450,
	tbar: toolbar, // <--- Toolbar
	maximizable: true,
	maskDisabled: true,
	bodyStyle: 'background-color:#fff',
	html: '<iframe id="container" src="http://www.google.com" style="width:100%;height:100%;border:none"></iframe>'
});
		
this.win.show();
As you have seen, these three ways to create a toolbar are very convenient for different situations, let's use the last one for this tutorial.

Add icons to the buttons

To add an icon to a button we need to create a CSS class where we will assign the icon we want as the background, let's define the background as "no-repeat" and add the property "!important" so the icon can be displayed correctly.
.back{
	background: url(icons/arrow_left.png) no-repeat !important;
}
Now we can use the property "iconCls" of the configuration object for our "toolbar".
var toolbar = new Ext.Toolbar({
	items: [
		{text:'Back',iconCls:'back'}, //<--- adding an icon to the button
		{text:'Forward'},
		{text:'Reload'},
		{text:'Stop'},
		{text:'Home'}
	]
});
Toolbar

Buttons with icons

Let's add the rest of the icons to the other buttons; the CSS classes have been defined in the HTML document.
var toolbar = new Ext.Toolbar({
	items: [
		{text:'Back',iconCls:'back'},
		{text:'Forward',iconCls:'forward'},
		{text:'Reload',iconCls:'reload'},
		{text:'Stop',iconCls:'stop'},
		{text:'Home',iconCls:'home'}
	]
});
Toolbar

Buttons with icons

By default the icon's alignment is to the left side of the button, but we can configure the alignment by using the property "iconAlign" which accepts the values "top", "right", "bottom" or "left". I'm going to use the property "defaults" of the toolbar to apply this configuration to all the buttons.
var toolbar = new Ext.Toolbar({
	defaults:{
		iconAlign: 'top' // <--- we change the icon position
	},
	items: [
		{text:'Back',iconCls:'back'},
		{text:'Forward',iconCls:'forward'},
		{text:'Reload',iconCls:'reload'},
		{text:'Stop',iconCls:'stop'},
		{text:'Home',iconCls:'home'}
	]
});
Toolbar

Changing the alignment of the icons

We can see that the position of the icon has changed, now the icon is displayed at the top part of the button, but if you look carefully you can see that the icon is aligned to the left, in order to correct this we need to specify the alignment in the CSS class where we defined the image.
.back{
	background: url(icons/arrow_left.png) center 0px no-repeat !important;
}
After this change we can see the icons centered on the button.
Toolbar

Centered icons on the button

Right-aligned buttons

When we need the buttons to be aligned to the right side of the panel we must use the component "Ext.Toolbar.Fill" to position the buttons in the right place.
var toolbar = new Ext.Toolbar({
	defaults:{
		iconAlign: 'top'
	},
	items: [
		{text:'Back',iconCls:'back'},
		{text:'Forward',iconCls:'forward'},
		{text:'Reload',iconCls:'reload'},
		{text:'Stop',iconCls:'stop'},
		{text:'Home',iconCls:'home'},
		new Ext.Toolbar.Fill(), // <--- we fill the empty space
		{text:'Bookmarks',iconCls:'book'}// now the following buttons are in the right side
	]
});
Toolbar

Buttons aligned to the right

We can also us the shortcut "->" for the component "Ext.Toolbar.Fill", in this way we will write less.
var toolbar = new Ext.Toolbar({
	defaults:{
		iconAlign: 'top'
	},
	items: [
		{text:'Back',iconCls:'back'},
		{text:'Forward',iconCls:'forward'},
		{text:'Reload',iconCls:'reload'},
		{text:'Stop',iconCls:'stop'},
		{text:'Home',iconCls:'home'},
		'->', // <--- shortcut for the Ext.Toolbar.Fill class
		{text:'Bookmarks',iconCls:'book'}// now the following buttons are in the right side
	]
});
Toolbar

This screen is the same as the previous one

A text box in the Toolbar

We're going to add a text box in the toolbar so the user can enter an URL and click on the button "search" and the iFrame will show the requested website.
var toolbar = new Ext.Toolbar({
	defaults:{
		iconAlign: 'top'
	},
	items: [
		{text:'Back',iconCls:'back'},
		{text:'Forward',iconCls:'forward'},
		{text:'Reload',iconCls:'reload'},
		{text:'Stop',iconCls:'stop'},
		{text:'Home',iconCls:'home'},
		'-', // <--- add a vertical separator bar between toolbar items 
		{xtype:'textfield',id:'url',width:250}, //<--- the textfield
		{iconCls:'goto'},
		'->', 
		{text:'Bookmarks',iconCls:'book'}
	]
});
Toolbar

Textfield, text button and vertical separator

The previous code has 3 important things, the first one is adding a vertical separator using a dash, this is actually a shortcut for the class "Ext.Toolbar.Separator"; the second important thing is that we're modifying the "xtype" of the button for a "textfield" (in this case), in this way we change the component type specifying the use of a text box instead of the button; the last important thing is that we're defining a button that has no text, only an icon.

Grouping buttons

With the new version of ExtJS (v3.0) we can form groups of buttons, this is useful when we need to separate the buttons by functionality from other buttons, for this example we're going to group the text box and the button "search".
var toolbar = new Ext.Toolbar({
	defaults:{
		iconAlign: 'top'
	},
	items: [
		{text:'Back',iconCls:'back'},
		{text:'Forward',iconCls:'forward'},
		{text:'Reload',iconCls:'reload'},
		{text:'Stop',iconCls:'stop'},
		{text:'Home',iconCls:'home'},
		'-',{
			xtype: 'buttongroup', // <--- grouping the buttons
			items:[
				{xtype:'textfield', id:'url', width:250},
				{iconCls:'goto'}
			]
		},
		'->', 
		{text:'Bookmarks',iconCls:'book'}
	]
});
Toolbar

Buttons grouped

We can also add a title to the group by using the property "title", we add it to the component "buttongroup", for this example we won't do that, but you can try if you want to and see the result.

“Split buttons” and menus

We're going to make the button "back" to show a menu of the sites we've visited, simulating in a way the brower history.
var toolbar = new Ext.Toolbar({
	defaults:{
		iconAlign: 'top'
	},
	items: [
		{
			text:'Back',iconCls:'back',
split: true, // <--- split the button
			menu:{ // <--- add a menu to the button
				items: [
					{text:'Yahoo!'}, // <--- This is an item for the menu
					{text:'Quizzpot'},
					{text:'Site point'}
				]
			}
		},
		{text:'Forward',iconCls:'forward'},
		{text:'Reload',iconCls:'reload'},
		{text:'Stop',iconCls:'stop'},
		{text:'Home',iconCls:'home'},
		'-',{
			xtype: 'buttongroup',
			items:[
				{xtype:'textfield', id:'url', width:250},
				{iconCls:'goto'}
			]
		},
		'->', 
		{text:'Bookmarks',iconCls:'book'}	]
});
Toolbar

Button with submenu

The previous code shows how we added a menu to the button "back", it's important to recall that every option of the menu can have another submenu.

Assigning actions to the buttons

Until now we have our browser's GUI ready but you can't do anything with it yet, so in the following lines I will show you how we can assign actions to the buttons of the toolbar. I'm going to modify the button "Home" so when the user clicks on the button it will redirect him to the home page, in this case "google.com".
//… code removed for simplicity
{
    text:'Home', iconCls:'home', 
    handler: function(){
        this.gotoUrl('http://www.google.com');
    }.createDelegate(this)
},
//… code removed for simplicity
The property "handler" receives a function where we can write all the actions we need the application to do when the user clicks on the button; the method "createDelegate" is necessary to change the scope of the anonymous function, in this way the variable "this" will refer to the object where the method "gotoUrl" (ToolbarTutorial) is found, inside of the anonymous function I'm executing a function that I haven't defined yet, but its purpose will be to change the "src" of the iFrame. Let's define the function that will show the requested website, we will use this method several times.
com.quizzpot.tutorial.ToolbarTutorial = {
	init: function(){
		//code removed
	},
	//this function changes the url of the iFrame
        gotoUrl: function(url){
		if(!Ext.isEmpty(url)){
			if(!/^http:\/\//.test(url)){
				url = 'http://'+url;
			}
			
			var iframe = Ext.get('container');
			iframe.dom.src = url;
			Ext.getCmp('url').setValue(url);
			this.win.setTitle(url +' - Quizzpot Explorer');
		}
	}
}
The previous function verifies that the parameter "url" has a value, then it validates that the value starts with "http://", if it doesn't start with that value the function will add it and will change the "src" of the iFrame, after doing that the url of the textbox and the window's title will be changed. Now I'm going to modify the button "Search" in order to get what's in the text box when the user clicks on it and then I will call the function "gotoUrl".
{iconCls:'goto',handler: this.search.createDelegate(this)}
In the previous code I didn't use an anonymous function, I only added a function of the object "ToolbarTutorial", so let's define that function right now:
com.quizzpot.tutorial.ToolbarTutorial = {
	init: function(){
//… code removed for simplicity
	},
	
	search: function(btn,event){
		this.gotoUrl(Ext.getCmp('url').getValue()); //<--- get the text the user wrote in the text box
	},
	
	gotoUrl: function(url){
		//… code removed for simplicity
	}
}
The function "search" only invokes the function "gotoUrl" with what's inside the text box.
Toolbar

Browser

Conclusions

In this tutorial we learned how to create a toolbar, how to use the buttons and how to create menus, also we learn how to add actions to the buttons. If you have any questions regarding today's tutorial you are welcome to join the forums and post there your questions or leave a message in this post. If you have a Twitter account, we invite to follow us so you can receive updates of this site.

Te gustaría recibir más tutoriales como este en tu correo?

Este tutorial pertenece al curso Learning Ext JS 3, te recomiendo revises el resto de los tutoriales ya que están en secuencia de menor a mayor complejidad.

Si deseas recibir más tutoriales como este en tu correo te recomiendo registrarte al curso, si ya eres miembro solo identifícate y registrate al curso, si no eres miembro te puedes registrar gratuitamente!

Si no gustas registrarte en este momento no es necesario! Aún así puedes recibir los nuevos tutoriales en tu correo! Jamás te enviaremos Spam y puedes cancelar tu suscripción en cualquier momento.

¿Olvidaste tu contraseña?

9Comentarios

  • Avatar-3 Florian Cargoet 29/08/2009

    Nice overview ! An alternative to .createDelegate(scope) is to use the scope config option : { text:'Home', iconCls:'home', handler: function(){ this.gotoUrl('http://www.google.com'); }, scope:this }

    • Avatar-4 Michael 18/02/2010

      Hello, I am having a problem getting this to work right. I am using ext-3.1.1 and when I run it, my images only show up directly behind my text. I cannot get it to move. Also, the 'Ext.Toolbar.Fill()' or '-&gt;' does not work. My BookMarks text and icon just show up on the left next to the rest of my buttons. It's like I am missing a js file or something. Can you give some advice?

      • Avatar-7 Crysfel 19/02/2010

        Hi Michael . Are you setting the "iconCls" property to the button? you can also set the icon position with the "iconAlign" property. good luck

        • Avatar-8 Michael 22/02/2010

          Here is a small part of my code: defaults:{ iconAlign: 'top' // values could be: 'top', 'bottom', 'right' &amp; 'left' }, items: [ {text:'Back', iconCls: 'back'} ,{text:'Reload', iconCls: 'reload'} so... yes I am setting the iconCls and I tried to put the image on top, but the image always shows up behind the text.

          • Avatar-11 César 21/01/2011

            Hola, gracias por los tutoriales y como podria hacer para que cuando yo carge una web siempre se cargue en el pequeño navegador y no me abra esa web en toda la pantalla y me saque de la aplicacion de ext gracias por tu ayuda.

            • Avatar-1 Marena 25/02/2011

              Perfect, keep walking!

              • Avatar-10 Lola 31/03/2011

                Hola Crysfel, en primer lugar, gracias por los tutos que me han sido muy utiles. He replicado tu ejemplo y me sale perfecto pero me gustaria saber como darle funcionalidad a los botones adelante y atras, refrescar y detener ya que he probado con las funciones usuales del navegador, history.back(), location.reload(), etc. pero no consigo que me funcionen con el navegador en Ext. Alguna idea?

                • Avatar-8 Martin 27/10/2011

                  hay alguna forma de agregar un boton a la altura de la cruz o el cuadrado de resize??? desde ya muchas gracias

                  • Avatar-10 Gilberto 22/08/2012

                    how can i change de 'text' poperty of an tbar item?

                    Instructor del curso

                    Crysfel3

                    Autor: Crysfel Villa

                    Software engineer with more than 7 years of experience in web development.

                    Descarga Código Fuente Ver Demostración

                    Regístrate a este curso

                    Este tutorial pertenece al curso Learning Ext JS 3, revisa todos los tutoriales que tenemos en este mismo curso ya que están en secuencia y van de lo más sencillo a lo más complicado.

                    Tendrás acceso a descargar los videos, códigos y material adicional.

                    Podrás resolver los ejercicios incluidos en el curso así como los Quizzes.

                    Llevarás un registro de tu avance.