Tuesday, January 20, 2009

extjs "sub menu" Using the Toolbar as a menu




This tutorial is about to answer some questions about how to build :
- the menu dynamically from data pulled from an external db, and that is working fine. However, the items off the main menu list are not expanding out to the right. Instead they drop down below the opening menu item. I took the example code with the static menu and pasted it into the same script and those behave properly - items and sub-menus push out to the right and then flow down.

- adding a combobox as an item in the menu bar.

- using inline UL/LI to create a menu using the excellent menubar component.

- use menubar/menuitems with buttons that have icons with no text.

- etc.

to do these please visit: http://extjs.com/forum/showthread.php?p=69007

Thursday, August 21, 2008

Release Notes for Extjs 2.2.0



Release Notes for Ext 2.2.0

Release Date: August 4, 2008
Current Version: 2.2.0 (rev 2547)
Previous Version: 2.1.0 (rev 2042)
Overview

* Full Firefox 3.0 support
* Added Ext.History component and sample
* Completely refactored Checkbox and Radio controls
* Added CheckboxGroup and RadioGroup components and sample
* Added MultiSelect and ItemSelector extensions and sample
* Added FileUploadField extension and sample
* Added XMLTreeLoader extension and sample
* Added several new Drag-and-Drop samples
* Added GMapPanel extension and sample
* Grid performance improvements
* Many general improvements and bug fixes
* Extensive documentation improvements
* Various locale file updates

Change Log

* Adapters
o Ext Base
+ Added UTF-8 to defaultPostHeader to support international char sets properly
* Ext.core
o Ext
+ New properties for isGecko2 and isGecko3
+ Updated useShims property to be Gecko2-only on Mac
+ Fix for isArray and array check fix in Ext.each
o Ext.Element
+ Event registration improvements
+ Updated Gecko/Mac overflow auto fix to be scoped to Gecko2 only
+ Shim border fix for IE8
o Ext.EventManager
+ Event handler registration logic refactored to fix DOM leak issues
o Ext.Updater
+ Now extends Ext.util.Observable
+ New overrideable getDefaultRenderer method
+ Fix in update method to preserve passed in config options correctly
* Ext.data
o Ext.data.Connection
+ New disableCachingParam config
o Ext.data.Record
+ Fixed type coercion bug in isModified
o Ext.data.Tree
+ New Node.isExpandable method
* Ext.util
o Ext.util.ClickRepeater
+ Fixed scope issue when unregistering interal event handlers
o Ext.util.Date
+ Various date format fixes
o Ext.util.Format
+ Fix in htmlDecode to handle ampersands correctly
+ New nl2br (newline to BR) function
o Ext.util.History
+ New component
o Ext.util.KeyMap
+ Added stopEvent as a valid config option for the addBinding method
* Ext.widgets
o Ext.Button
+ Fixes to minimize mouse handlers created on buttons
o Ext.Component
+ New initPlugin method for more flexible plugin initialization
+ Fix to ignore state events if stateful=false
o Ext.Container
+ Updated onDestroy to call destroy on the container's layout if available
+ Fixed default scope passed to the cascaded function in Container.cascade
o Ext.DatePicker
+ Marked constrainToViewport config as deprecated (it's not currently used)
+ Changed disabledDaysText and disabledDatesText to default to "Disabled" instead of ""
+ New configs for minDate, maxDate, disabledDays, disabledDaysRE and disabledDates
+ New methods setDisabledDates, setDisabledDays, setMinDate and setMaxDate
+ New showToday config to show/hide the Today button and footer
+ Fixed selectToday to check for disabled Today button before changing the date
o Ext.DataView
+ New mouseenter and mouseleave events
+ New trackOver config to enable mouse events
+ Fix in getNodes to calculate the end node correctly
o Ext.Editor
+ New canceledit event
+ Fixed issue with TriggerField editors not blurring correctly on key navigation
+ Fixed editor wrapper element scrollbar issue in FF2/Opera
o Ext.PagingToolbar
+ Added beforechange and change events and changePage method
+ Fixed handling of 0 entered into the page field
o Ext.Panel
+ Change to set ownerCt on buttons added to panels
+ Fix for FF2/Mac scroll bar issue on contained items
+ Fix panel disabling support in IE
+ Fixed in destruction order of internal components
o Ext.ProgressBar
+ Fix to only attempt progress updates if rendered
+ Added support for the text config in the wait method
+ Fix for preserving the proper progress width in ratio to the value on resize
o Ext.QuickTips
+ Added autoRender support to fix initial display issues
o Ext.Resizable
+ Change to render the resize proxy to the document body instead of as a sibling to its element so it doesn't interfere with Component position calculations
o Ext.Slider
+ New dragging property and changecomplete event
+ Fixes for slider with minValue != 0
+ Fix for preserving the proper thumb position in ratio to the value on resize
o Ext.StatusBar
+ Fix for setting the proper default icon on clear
o Ext.TabPanel
+ Fix to position the tab strip spacer element correctly for tabPosition bottom
+ Fix for FF3 to raise the contextmenu event correctly on tab strip right-click
o Ext.Tip
+ Fixed IE7 repaint bug on initial show
o Ext.Toolbar
+ Fix in addField to add the fields to the items collection rather than the Toolbar items
o Ext.Window
+ Added doLayout call on resize
o Ext.dd.DDCore
+ Fixed null error in isValidHandleChild
o Ext.dd.ScrollManager
+ Fix to enable overriding scroll frequency in the scroll config object
o Ext.dd.StatusProxy
+ Fix to remove float style from ghost elements when adding them to the proxy to prevent proxy box collapse
o Ext.form.Checkbox
+ Completely refactored to support new visual styles
o Ext.form.CheckboxGroup
+ New component
o Ext.form.DateField
+ New showToday config to show/hide the Today button and footer on the associated DatePicker
+ New methods setDisabledDates, setDisabledDays, setMinValue and setMaxValue
o Ext.form.Field
+ Fix to prevent initializing the data value to emptyText
+ Fix to preserve the originalValue on init
+ Fix for odd FF/Win issue when changing OS window focus that disabled editing
+ Change to default error messages to basic tooltips if no field container el is available
o Ext.form.FormPanel
+ Change to make the form tag into the panel's body element
o Ext.form.HtmlEditor
+ Scoped disabling the font, link, lists and source edit buttons to Safari2 only (Safari3 is OK)
+ Various fixes to improve initialization
+ Fix to prevent multiple event handlers from being setup (resolved double line break issue in IE)
+ Fixed issue of IE allowing toolbar commands to apply to content outside the editor body
o Ext.form.Label
+ Added setText method
o Ext.form.TextArea
+ Fixed onKeyUp not calling its superclass method
o Ext.form.TimeField
+ Fix for broken field on DST boundary dates
o Ext.form.TriggerField
+ Fix for trigger icon alignment to field in IE
+ Fixed missing scope to properly remove the document mousedown handler after mimicing blur
o Ext.form.Radio
+ Completely refactored to support new visual styles
o Ext.form.RadioGroup
+ New component
o Ext.form.TextField
+ Fix for selectOnFocus support
+ Fixed broken key filtering when using maskRe in non-FF browsers
o Ext.grid.ColumnModel
+ Fixed configchange event declaration name typo
o Ext.grid.EditorGrid
+ Fix to align editors correctly with mixed-height row content
+ Fixed bug in preEditValue that prevented html decoding when needed
+ Added onDestroy method to clean up column model's editors on destroy
o Ext.grid.GridPanel
+ New deferRowRender config
o Ext.grid.GridView
+ New configs for controlling cell and row selector class and depth
+ Fixes to sync the invisible focus element on row add/remove actions
+ Moved some rendering logic to afterRender (improved performance)
o Ext.layout.BorderLayout
+ Added destroy method to clean up splitbars created by layout
o Ext.layout.ColumnLayout
+ Target size calculation fix for IE
o Ext.layoutContainerLayout
+ Added support for subclass destroy functions
o Ext.menu.Item
+ Improved tolerance for mousing from a menu to its submenu without dismissing the submenu too quickly while passing over other menu items
o Ext.menu.Menu
+ New ignoreParentClicks config to ignore clicks on menu items with child menus
o Ext.menu.TextItem
+ Updated constructor to support config object in addition to just text
o Ext.tree.TreeDragZone
+ Fix to honor the hlDrop config on invalid drop repair
o Ext.tree.TreeDropZone
+ Fixed highlight calls to check enableFx first to avoid possible errors
o Ext.tree.TreeEditor
+ Fixed editor alignment to node when autoScroll is on and the node is outside the scroll area
o Ext.tree.TreeLoader
+ Fixed type coercion bug in isLoading
+ Updated createNode to support new TreePanel.nodeTypes
o Ext.tree.TreeNode
+ New getLoader method
+ Fixed null error in destroy when no child nodes present
o Ext.tree.TreeNodeUI
+ Refactored internal support for Ext.data.Node.isExpandable
o Ext.tree.TreePanel
+ Ability to specify dataUrl or a TreeLoader config in addition to a TreeLoader instance
+ New nodeTypes support for more flexible node declaration and creation

AJAX Ext js 2.2.0: History, Selectors, FileUploader



AJAX Ext js 2.2: History, Selectors, FileUploader



New features include:


CheckboxGroup / RadioGroup


Technically, while the individual Checkbox and Radio controls are not new, they may as well be, considering the overhaul they have had in this release. Gone are the ugly standard browser input controls, now replaced by attractive, visually-consistent Ext-ified versions (a long-overdue improvement).


In addition to that, we’ve added group controls for both that support complex layouts with just a config option or two. Previously in order to accomplish similar grouping layouts you would have had to create a container with a ColumnLayout and manually place your controls across multiple column configs.


History


Another component that has been missing in Ext is a browser history utility to enable history stack navigation within your single-page Ext application. The new Ext.History singleton makes it extremely easy to do exactly that, and it uses an event-based API to notify you when the browser history as changed.


MultiSelect / ItemSelector


These two components were contributed to Ext by community member TJ Stuart (thanks TJ). The MultiSelect is a traditional list control that allows for selecting multiple list items, and the ItemSelector combines two MultiSelects into a more sophisticated control that includes drag-and-drop list selection and bulk selection and deselection among other features.


FileUploadField


This is an official extension provided as a sample for implementing a useful form component. Not everyone needs a form upload component, but if you do, you can’t live without it. This control is fully styled and has an API consistent with other Ext form controls. It also supports both Text+Button (read-only text) and Button-only modes, and can participate fully in form layouts.


XmlTreeLoader


This official extension provides a great demonstration of extending an existing Ext component to provide functionality that you need in your own application. Again, loading an XML document into a tree is not needed by everyone, but if you do need something similar, this should be a great demo.


GMapPanel


This extension was originally written up as a demo for one of our previous blog posts. However, it proved to be such a hit with the community that we transformed it into an official extension. This is another useful example of extending a standard Ext component, in this case to interface with an external API.

Friday, August 8, 2008

AJAX with ExtJS JavaScript Framework

Ext JS, the JavaScript framework with Ajax and UI Components


Ext JS, the JavaScript framework with Ajax and UI Components


Ext JS is a JavaScript Library/Framework which works in conjunction with Prototype, YahooUI and jQuery. It’s probably the most exciting toolkit available for building web 2.0 websites right now. It’s jam packed with features, and is designed to make life much easier for building great UI in JavaScript.


I’ll not dig to deep right now, I suggest you check out the example and demos first to see what you think.


Below is a the script used to grab XML data via Ajax and populate a grid (sortable table like object):


/*
* Ext JS Library 1.0.1
* Copyright(c) 2006-2007, Ext JS, LLC.
* licensing@extjs.com
*
* http://www.extjs.com/license
*/

Ext.onReady(function(){

// create the Data Store
var ds = new Ext.data.Store({
// load using HTTP
proxy: new Ext.data.HttpProxy({url: 'sheldon.xml'}),

// the return will be XML, so lets set up a reader
reader: new Ext.data.XmlReader({
// records will have an "Item" tag
record: 'Item',
id: 'ASIN',
totalRecords: '@total'
}, [
// set up the fields mapping into the xml doc
// The first needs mapping, the others are very basic
{name: 'Author', mapping: 'ItemAttributes > Author'},
'Title', 'Manufacturer', 'ProductGroup'
])
});

var cm = new Ext.grid.ColumnModel([
{header: "Author", width: 120, dataIndex: 'Author'},
{header: "Title", width: 180, dataIndex: 'Title'},
{header: "Manufacturer", width: 115, dataIndex: 'Manufacturer'},
{header: "Product Group", width: 100, dataIndex: 'ProductGroup'}
]);
cm.defaultSortable = true;

// create the grid
var grid = new Ext.grid.Grid('example-grid', {
ds: ds,
cm: cm
});
grid.render();

ds.load();
});

Take a look at the JavaScript generated grid here.


Hopefully this short intro will wet your appetite, more to come soon.


Great work Jack (and the rest of the Ext JS team) for this superb library, can’t wait to see more!!



JavaScript Form Validator number two



Well it validates your form stupid!! as with most (if not all?) posts on this website, the script is simple, easy to follow and not jam packed with to many features. Basically this script will look for required fields (which you specify in your form.. I’ll come to this later) and if a required field is empty, it will through up a JavaScript alert box telling the user (and prevent the form from being submitted).


Before I present to you the Code Example, I’ll explain a little about how to configure your form and make certain fields required.

For simplicity, I’ve chosen to make use of the fields ‘Title’ tag. This is where you make fields required.


For example: < input type="text" name="FirstName" title=”required” >


Note: The script will support the following form field types:



  • Text

  • Textarea

  • Password

  • Select


Just to recap. To make any of the supported fields required, just add title=”required”!


Triggering the form to call the JavaScript Validation Script:

In order for the form to call the JavaScript and check all the required fields, we need to prevent the form from submitting. In order to achieve this, we will use the onSubmit event on the form tag. Example:


< form name="myForm" method="post" action="process.php" onSubmit=”return myForm.check(this)” >


We must use return before the function call, this tells to form ‘do not submit the form unless the function returns true’.


The JavaScript form Validator Script



var myForm = {
fTitle : "",
fValue : "",
fName : "",
fField : "",

check : function(fObject) {
for(var i = 0;i < fObject.elements.length;i++) {
fField = fObject.elements[i];
fTitle = fField.title;
fValue = myString.trim(fField.value);
fName = fField.name;
fType = fField.type;
switch(fType) {
case "text":
case "password":
case "textarea":
if(fTitle == "required" && encodeURI(fValue).length < 1) {
alert(fName+': is required, please complete.');
fField.focus();
return false;
} // if
break;
case "select-one":
if(fTitle == "required" &&
fField.options[fField.selectedIndex].value.length < 1) {
alert(fName+': is required, please select one.');
fField.focus();
return false;
} // if
break;
} // switch
} // for
} // method
} // object

var myString = {
trim : function(s) {
return s.replace(/^\s+/, '').replace(/\s+$/, '');
}, // method
noTags : function(s) {
return s.replace(/<\/?[^>]+>/gi, '');
},
strip : function(s) {
return this.noTags(this.trim(s));
}
}

As you can see, this is nice and easy to follow. Nothing to fancy, but believe me this wee function can save a lot of time, especially if you build a lot of forms.


Why does it not do more complex validation?

Simple, because I like to keep things nice and easy (and I don’t do complex)…. The last thing I want to do is give you a headache. Like everything on this site, this is just an example. Please feel free to use and enhance it to fit better with your own needs.


Before I go, I’d better mention that the JavaScript function will strip out any leading and trailing whitespace before the validation is done. There is also a little function to strip out HTML tags (it’s not being used in the above example, but you can make use of this on a field basis by using the onFocus event!!), Just a little bonus!!

AJAX stands for Asynchronous JavaScript And XML.

AJAX stands for Asynchronous JavaScript And XML.


AJAX = Asynchronous JavaScript and XML
AJAX is not a new programming language, but a technique for creating better, faster, and more interactive web applications.


With AJAX, your JavaScript can communicate directly with the server, using the JavaScript XMLHttpRequest object. With this object, your JavaScript can trade data with a web server, without reloading the page.
AJAX uses asynchronous data transfer (HTTP requests) between the browser and the web server, allowing web pages to request small bits of information from the server instead of whole pages.


The AJAX technique makes Internet applications smaller, faster and more user-friendly.


AJAX is a browser technology independent of web server software.



AJAX is Based on Web Standards


AJAX is based on the following web standards:


  • JavaScript

  • XML

  • HTML

  • CSS


The web standards used in AJAX are well defined, and supported by all major browsers. AJAX applications are browser and platform independent.


AJAX is About Better Internet Applications


Web applications have many benefits over desktop applications; they can reach a larger audience, they are easier to install and support, and easier to develop.

However, Internet applications are not always as "rich" and user-friendly as traditional desktop applications.
With AJAX, Internet applications can be made richer and more user-friendly.
AJAX is based on existing standards. These standards have been used by most developers for several years.


AJAX Uses HTTP Requests


In traditional JavaScript coding, if you want to get any information from a database or a file on the server, or send user information to a server, you will have to make an HTML form and GET or POST data to the server. The user will have to click the "Submit" button to send/get the information, wait for the server to respond, then a new page will load with the results.


Because the server returns a new page each time the user submits input, traditional web applications can run slowly and tend to be less user-friendly.


With AJAX, your JavaScript communicates directly with the server, through the JavaScript XMLHttpRequest object


With an HTTP request, a web page can make a request to, and get a response from a web server - without reloading the page. The user will stay on the same page, and he or she will not notice that scripts request pages, or send data to a server in the background.

AJAX is WEB 2.0 programming technology


What is AJAX?


AJAX is an acronym for Asynchronous JavaScript and XML. It is a development technique for creating interactive web applications. Unlike classic web pages, which must load in their entirety if content changes, AJAX allows web pages to be updated asynchronously by exchanging small amounts of data with the server behind the scenes.


AJAX uses a combination of:



  • CSS, for marking up and styling information.
  • The Document Object Model accessed with a client-side scripting language like JavaScript
    to dynamically display and interact with the information presented.
  • The XMLHttpRequest object to exchange data asynchronously with the web server.
  • XML is sometimes used as the format for transferring data between the server and client,
    although any format will work.

Talking to the Server


Once the DOM event has occurred on the webpage, we need to obtain an XMLHttpRequest Object. This is
done using a function like the following. We need to write it this way to accommodate different browsers.
Notice that we set the callback function using onreadystatechange.




var obj;

function ProcessXML(url) {
// native object

if (window.XMLHttpRequest) {
// obtain new object
obj = new XMLHttpRequest();
// set the callback function
obj.onreadystatechange = processChange;
// we will do a GET with the url; "true" for asynch
obj.open("GET", url, true);
// null for GET with native object
obj.send(null);
// IE/Windows ActiveX object
} else if (window.ActiveXObject) {
obj = new ActiveXObject("Microsoft.XMLHTTP");
if (obj) {
obj.onreadystatechange = processChange;
obj.open("GET", url, true);
// don't send null for ActiveX
obj.send();
}
} else {
alert("Your browser does not support AJAX");
}
}


AJAX: Here are the attributes and methods for the XMLHttpRequest Class:

Attributes
























readyState The readyState code changes value from 0 to 4 during a request cycle:
0: not initialized.

1: connection established.

2: request received.

3: processing.

4: finished and response is ready.

status 200: "OK"

404: Page not found.
onreadystatechange callback method assigned via this attribute
responseText holds the response data as a string of characters.
responseXml holds the response data as XML
data.

Methods













open(mode,
url, boolean)
mode: type of request: GET or POST

url: the location of the file

boolean: true (asynchronous) or false (synchronous).
send("string")
null for a GET command (in native mode; null not passed with ActiveX)



Here is an example of a callback function which is registered via the onreadystatechange attribute.




function processChange() {
// 4 means the response has been returned and ready to be processed
if (obj.readyState == 4) {
// 200 means "OK"
if (obj.status == 200) {
// process whatever has been sent back here:
// anything else means a problem
} else {
alert("There was a problem in the returned data:\n");
}
}
}


The Rest of the Pieces



Let's use the functions we presented above in a little application to show how all the pieces fit together. We will
allow a user to enter a user name, then send that name to a server to check that it is not in use by anyone else.



First, our html:




<BODY>
Enter your Username: < id="username" name="username" type="text" onblur="checkUserName(this.value,'')" >
</BODY>


And here is the missing piece on the client side: The function called from the html which gets the whole process going.




function checkUserName(input, response) {
// if response is not empty, we have received data back from the server
if (response != '') {
// the value of response is returned from checkName.php: 1 means in use
if (response == '1') {
alert("username is in use");
} else {
// if response is empty, we need to send the username to the server
url = 'http://localhost/xml/checkName.php?q=' + input;
ProcessXML(url);
}
}
}


Note that the response value must actually be parsed from either text or XML returned
from the server. The processChange() callback receives the returned data.
Here is a little more detail on what happens in that function:




function processChange() {
// 4 means the response has been returned and ready to be processed
if (obj.readyState == 4) {
// 200 means "OK"
if (obj.status == 200) {
// process whatever has been sent back here:
// we need to parse the returned data (text or XML)
// and then call checkUserName again with response set
// to the appropriate value.
// anything else means a problem
} else {
alert("There was a problem in the returned data:\n");
}
}
}


All we need to make it all work is a server-side script or servlet to catch the GET request, do the check
on the user name, and return the response. Here is an example in PHP - everything is hard-coded which is
not what it would really look like, but you get the idea.




<?php header('Content-Type: text/xml');

function checkName($q) {
if (isset($q)){
switch(strtolower($q)) {
case 'maggie' :
return '1';
break;
...
default:
return '0';
}
} else {
return '0';
}

}
?>



Google and AJAX



AJAX has gained popularity over the past few years due in part to Google's use of the technology
in Gmail, Google Maps, and other web-based applications.


The interesting thing about this search capability is that users don't have to leave the page to do a search,
as results are loaded right below the search box using AJAX. Search results are sorted into 4 different
categories: local, web, video, and blogs, and can be displayed in a list or with tabs.
In addition, users can use the copy button on results to add them to other content (such as blog
post comments).


More Examples and Tutorials



Here are additional examples and tutorials on AJAX:







AJAX stands for Asynchronous JavaScript And XML.


AJAX is a type of programming made popular in 2005 by Google (with Google Suggest).


AJAX is not a new programming language, but a new way to use existing standards.


With AJAX you can create better, faster, and more user-friendly web applications.


AJAX is based on JavaScript and HTTP requests.