Category Archives: ExtJs

Sencha Touch – One Way to Implement Autosuggest Textbox

Hello,

Recently in one of our Sencha Touch project there was a requirement to add autosuggest textbox. As user starts typing there should be some suggestions and user should be able to either select one of the option or type in the value. In this blog I am going to explain the approach I used for that. Please note that there could be other ways to implement this.

First lets create a store that has the options for auto suggestions. For that here is the model definition.

Ext.define(‘MyApp.model.Option’, {
    extend:’Ext.data.Model’,
    config:{
        fields:[
            { name:’id’, type:’int’ },
            { name:’text’, type:’string’ },
        ],
        idProperty: ‘id’
    }
});

Now lets create a store which holds the data.

Ext.define(‘MyApp.store.Option’, {
  extend: ‘Ext.data.Store’,
  config: {
    model: ‘MyApp.model.Option’,
    autoLoad: true,
    proxy: {
      type: ‘memory’
    },
    data : [
        {id: 1,    text: “Option 1”},
        {id: 2, text: “Option 2”},
        {id: 3, text: “Option 3”},
        {id: 4, text: “Option 4”}
    ]
  }
});

Now our approach is quite simple we will create a floating panel with list and assign this store to it and as soon as user starts typing in textbox, we will show this panel near to textbox and filter store with what is typed in textbox. So lets create a floating panel.

Ext.define(‘MyApp.view.Traffic.AutoSuggestPanel’, {
extend: ‘Ext.Panel’,
xtype: ‘autosuggestpanel’,
config: {
modal: true,
hideOnMaskTap: true,
hidden: true,
height: ‘180px’,
width: ‘94%’,
layout: ‘fit’,
margin: ‘-9px 0 0 0’,
items: [
{
xtype: ‘list’,
id: ‘autoSuggestList’,
itemId: ‘autoSuggestList’,
itemHeight: 30,
itemTpl: ‘<div style=”font-size: 13px”>{name}</div>’,
store: ‘Option’
}
]
}
});

We will add this panel to viewport when app launches, as you see it’s hidden initially so it will not be visible.

Ext.Viewport.add(Ext.create(‘MyApp.view.Traffic.AutoSuggestPanel’));
Now lets add keyup event to textfield on which we want to show this suggestions. Also we will add our floating panel as reference to controller.
 config: {
        refs: {
              autoSuggestPanel: ‘autosuggestpanel’
              autoSuggestList: ‘#autoSuggestList’,
              autoSuggestTextField: ‘#autoSuggestTextField’
       }
}
autoSuggestTextField: {
            keyup: ‘onAutoSuggestTextFieldKeyUp’
            },
autoSuggestList: {
            itemtap: ‘onAutoSuggestListItemTap’
            },
And define it’s handler in controller.
onAutoSuggestTextFieldKeyUp: function(text){
        if( this.getAutoSuggestPanel().isHidden( ) ) {
            this. getAutoSuggestPanel().showBy(text,’bc-tc’ );
        }
        Ext.getStore(‘Option’).clearFilter();
        Ext.getStore(‘Option’).filter(‘text’,text.getValue());
}
Above code will show auto suggest list next to textfield. Now we have to add itemtap event for the list and set it’s value in textbox. Here is handler for it.
onAutoSuggestListItemTap: function(list, index, target, record){
        var name = record.get(‘text’);
this. getAutoSuggestPanel().hide();
       this.getAutoSuggestTextField().setValue(name);
}
That’s it and you have autosuggest textbox ready.

Sencha Touch List, Different background colors for Group Header

Recently in one of my project we have a Sencha Touch list with grouped headers. We know that we can control group header styles by CSS or we can change it by overriding base css class. In this case we will have one same color for each group header, while in my case the requirement was to have different background colors for each group header. This blog is about how how I implement it, you may have better idea. Feel free to comment.

Here I added background color in each items of the list and then grouped it based in certain field. For example.

Ext.define(‘MyApp.model.MyModel’, {
    extend: ‘Ext.data.Model’,
    config:{
        fields: [
            { name:’id’, type:’int’},
            { name:’group_background_color’, type:’string’},
            { name:’item_name’, type:’auto’},
            { name: ‘group’, type: ‘string’}
        ]
    }
})

Then we have following Store definition.

Ext.define(‘MyApp.store.MyStore’, {
    extend: ‘Ext.data.Store’,
    config: {
        model: ‘MyApp.model.MyModel’,
        autoLoad: true,
        grouper: {
        groupFn: function (item) {
            return item.get(‘group’);
            }
        },
        proxy: {
            type:’ajax’,
            actionMethods:{
                read: ‘POST’
            },
            url:’items.json’,
            reader:{
                type:’json’,
                rootProperty:’items’
            }
        }
    }
});

Now we have our list where we will show this data.

{
        xtype: ‘list’,
        id:’myList’,
itemId:’myList’,
scrollable: true,
grouped: true,
itemTpl:'<div>{item_name}</div>’ ,
        store: ‘MyStore’
}

This will create list with groups and group header. If you use default Sencha Theme the group header will have blue as background color. We have to change it to our colors dynamically. For that we will update on list refresh. List refresh event is fired when list is visible first time and there is some change in data in store or list store is loaded. Add refresh event in controller.

control:{
            ‘#myList’:{
                refresh: ‘refreshListHeaders’
            }
}

And here is the function.

refreshListHeaders: function(list){
    if(list.groups){
    var groupElements  = document.getElementsByClassName(‘x-list-header’);
    for(var i=0;i < groupElements.length i++){     
       var firstChild = list.groups[i].children[0];    var backGroundColor = firstChild.data.banner_background_color;
    groupElements[i+1].style.setProperty(‘background-color’, backGroundColor, ‘!important’);
    }
    }
    }

So our logic is very simple. We get all the elements with class name “x-list-header” . That gives us all the header elements.  Now for each group we are getting background color from the first item of the group and set it as background color to group header.

TinyMCE Editor Height Issue in ExtJs Application

Hello,

This is another blog post on TinyMCE editor in ExtJs application, Have you ever noticed that If you use TinyMce editor in ExtJs application there are some issues with height. Sometimes it takes more height then you specified and that might destroy your layout completely. This is due to internal calculations and logic of TinyMCE editor.

The logic is wrong in two ways. First thing is that it always assume that minimum height of TinyMCE editor should be 100 so if you give height less then 100. It will always take it as 100 and hence your layout is wrong. Because outer div of editor will show the height which you gave but it’s actual height would be different.

Second issue is that it does not take care of editor’s tool bar where you have all the controls. Actually editor’s height should be height which you specified minus height of control toolbar. Which actually is not the case. It gives separate height to toolbar. For example if you set height of your editor to 100. It actually set height to 128. 100px height of editor and 28px height of toolbar controls so it’s totally wrong. So what is the solution?

Well the solution is in the TinyMCE src file. You will have tiny_mce_src.js file in your app. There go to line no 13301 approximately. There you will see following line.

mh = s.min_height || 100;

This is where the issue is. If you give height less then 100 it will always take 100 as minimum height. So change it as follow.

mh = s.min_height || s.height;

Now it will take minimum height which you specified. Now go to line no 13426 approximately.  Here change the height from

height : h

to

height : h-28

That’s it and all your issues related to heights are resolved.

It took 4 hours for me to find the solution so I hope this post saves your time.

Thanks.

TinyMCE editor in ExtJs Application Returns Old Value.

Hello,

Finally I got some to add some more interesting blogs. Recently I have faced an issue with TinyMCE editor in ExtJs application. The issue was little wired. We have a TinyMCE editor in ExtJs form panel where it’s disabled first. There is a button in form panel which enables. After that if we update any value in TinyMCE editor, it shows on screen but when we get value from form panel, the value of TinyMCE field is always the old one.

After struggling for some hours, I find out the issue. When TinyMCE is disabled, there are no events of active editor. But when we enable it editor should be initialized properly and all the event handlers should be attached. However it’s not happening. So what is the solution for it. Change the logic of TinyMCE intilization and add key up event.

setup : function( ed ) {
ed.onKeyUp.add(function(ed) {
tinymce.activeEditor.save();
});
}

This you can find it your TinyMCEHtmlEditor.js file. What it does is it saves the state of current active editor when we type something it it. This logic works when you have more then one TinyMCE editor in single form. Because when you are typing inside it tinymce.activeEditor gives instance of current active editor and keyup events save its state. So when you getValue of editor, it reflects the new value.

Hope this helps you.

ExtJs Window Resize on Browser Resize

In this blog, I will explain how to resize all the modal window on ExtJs on browser resize. In one of my recent project, I had a requirement to resize all the modal windows open at the same time on browser resize.  Following is the solution.

You must have some main view of app which should be rendered first when app starts. You have to add render event of that view as follow.

this.control({
‘mainView’: {
render: this.onMainViewRender
        }
});

Now add the following function in your controller file.

onMainViewRender: function() {
Ext.EventManager.onWindowResize( this.onBrowserResize, this );
}

Above function binds the browser resize event and add a callback function to it. Following is the function definition of onBrowserResize

onBrowserResize: function( width, height ) {

Ext.WindowManager.each( function( window ) {

if( !window.isXType( ‘window’ ) )
                return;                      
if( height < 600 ) {
                                window.maxHeight = height – 30;
                                window.doLayout();
                                window.center();
                        } else {
                                window.maxHeight = 600;
                                window.doLayout();
                                window.center();
                        }
                });
}

It might be possible that we have some message box open at that time so we have to ignore it. That’w why we are checking the window xtype. Here we are setting maxHeight of window. 600 is just the example here. You can change it with your own preference. Else loop is to restore window to it’s original height and width if browser is resized to bigger height and width than window.

Hope this helps you.

Synchronize ExtJs Grid vertical Scrollbar

Recently I was working on ExtJs project in which there were two grids side by side and requirement was to synchronize scrollbar of both grids. See the picture below.

If user moves vertical scrollbar of left grid right grid scrollbar should be moved automatically and vice versa.

So how to do that? Following is the trick. Suppose left grid object is leftGrid and right grid object is rightGrid variables.

var leftGridScroller = leftGrid.getVerticalScroller();
  leftGridScroller.on({
    ‘bodyscroll’: function (event) {
       var rightGridScroller = rightGrid.getVerticalScroller();
       rightGridScroller.el.dom.scrollTop =  leftGridScroller.el.dom.scrollTop;
     }, scope: this
});

And Same way for right hand side grid.

var rightGridScroller = rightGrid.getVerticalScroller();
  rightGridScroller.on({
    ‘bodyscroll’: function (event) {
       var leftGridScroller = leftGrid.getVerticalScroller();
       leftGridScroller.el.dom.scrollTop = rightGridScroller.el.dom.scrollTop;
     }, scope: this
});

This code will work only when you have scroller visible. Else getVerticalScroller will return undefined. So ypu must check for it if you are not sure about number of records in grid.

Same way one can synchronize horizontal scrollbar using above code. Only thing need to change is, you have to use getHorizontalScroller function instead of getVerticalScroller. For horizontal scroller property is scrollLeft.

Same trick can be applied to ExtJs panel scrollbar. Here you can get object of scrollbar using docekdItems if you are using ExtJs version 4.x.x. Please not that thise example is of ExtJs 4.0.2a.

ExtJs 4.0.2 – Print Grid

Recently I tried ExtJs 4.0.2a. Here I am going to share a trick to print ExtJs grid. Concept is to open a new window. Render grid inside window and print grid.

Add a button in toolbar of grid panel. Call it a print button. Set handler for the button and add following code in handler. First of all open a new window.
var printDialog = window.open(”, ‘PrintPortfolioGrid’);
Add some basic HTML to newly open a window. Most important thing is to add link to ExtJS core files and CSS so we can properly render grid.
var html = ‘<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN”‘
            ‘”http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”>’ +         
            ‘<html>’ +
            ‘<head>’ +
            ‘<title>Print Portfolio Grid</title>’ +
            ‘<ink rel=”stylesheet” type=”text/css” href=”ext-4.0.2a/resources/css/ext-all.css” />’ +
            ‘<link rel=”stylesheet” type=”text/css” href=”styles/Triskell.css” />’ +
            ‘<script type=”text/javascript” src=”ext-4.0.2a/ext-debug.js”></script>’ +
            ‘</head>’ +
            ‘<body></body>’ +
            ‘</html>’;
printDialog.focus();
printDialog.document.write(html);
printDialog.document.close();
Now add some events to initialize document and Ext so that we can render grid.
printDialog.onload = function () {
            printDialog.Ext.onReady(function () {
                printDialog.Ext.create(‘Ext.grid.Panel’, {
                    store: printDialog.Ext.create(‘Ext.data.Store’, {
                        fields: [‘Name’,’Cost’],
                        data: [
                                { Name: ‘IT Portfolio, Cost: ‘1500$’},
                                { Name: ‘Product Portfolio’, Cost: ‘2500$’},
                                { Name: ‘Asset Portfolio’, Cost: ‘4500$’},
                                { Name: ‘NPD Portfolio’, Cost: ‘3500$’},
                            ]
                    }),
                    renderTo: printDialog.Ext.getBody(),
                    columns: [
                                   { header: ‘Name’, dataIndex: ‘Name’, flex: 1 },
                                   { header: ‘Cost’, dataIndex: ‘Cost’, flex: 1 }
                                  ],
                    width: 723,
                    height: 500
                });
                printDialog.print();                
            });
        }
That’s it and it will open a print dialog.Select a required printer and it will print your grid.

ExtJs MVC- Dynamically Load Views

Hello,

Recently I tried ExtJs 4.0.2a and MVC application architecture and I must say that’s an awesome improvement. Using MVC you have so much of flexibility. Now you can organize your whole application in proper structure that can be easily maintained and updated. It’s really powerful feature available in ExtJs 4.0. You can get more details about this from this link. The MVC Architecture

They have explained a straight forward application with a grid with CRUD operations. What I will explain is dynamically loading views. Please read above article before further reading this post.

I was having requirement to dynamically load different views on all the the use actions. For example I have following four views for my content panel.

app/view/content/UsersGrid.js
app/view/content/ProjectsGrid.js
app/view/content/PremimumUsersGrid.js
app/view/content/PortfolioGrid.js

and let’s say I have assigned following aliases to all of the above views.

UsersGrid => ‘UsersGrid’
ProjectsGrid => ‘ProjectsGrid’
PremimumUsersGrid => ‘PremimumUsersGrid’
PortfolioGrid => ‘PortfolioGrid’

I have a content panel in my view port and in which above views would be loaded dynamically. I can add reference of ContentPanel in my content controller to get the instance of it dynamically.

refs: [
        {
            ref :  ‘contentPanel’,
            selector: ‘ContentPanel’
        }
]

refs is the new way in MVC to get the reference of the the control. Above code will create a function getContentPanel() dynamically and I can use it to get reference of Content Panel. Here ref property specify name of function. Selector specify xtype of control. This xtype can be set using alias as follow.

alias : ‘widget.ContentPanel’

Now consider I have a button. On click of button I want to load UsersGrid. Following will be code to load content panel and creating and adding view dynamically.

var contentPanel = this.getContentPanel();
contentPanel .removeAll(); //removing existing views.

var usersGrid = Ext.create(‘MyApp.view.Content.UsersGrid’);

contentPanel.add(usersGrid);
contentPanel.doLayout();

Same way you can load other views as well.

Small Tips for ExtJs Programming

Hello,

Here I am sharing some tips that would be useful for you while working with ExtJs. These tips are about issues I faced while working on ExtJs projects.

1) Get-Set ExtJs Panel HTML

I don’t know how many of you faced this issue. While working on one project, requirement was to set panel HTML dynamically. If you check Panel class there is not any method like getHtml() setHtml(). Following is the solution for it.

var dynamicHtml = ‘<div> This is dynamic HTML</div>’;
myPanelObj.body.dom.innerHTML = dynamicHtml;

This will set panel HTML. Same way you can get panel HTML using myPanelObj.body.dom.innerHTML.

2) ExtJs Window me.Events are undefined error

If you are extending ExtJs window and on creating object of extended control, if you get above error then you forgot to call base class constructor. Call the base class constructor using following code.

ExtendedWindowObject.superclass.constructor.call(this, config);

3) Set padding while using ExtJs panel table layout.

When you use table layout in ExtJs panel layout. All the controls are arranged in a table. Sometimes it does not look good if you don’t give padding to it. It looks very clumsy. So to give padding give id to panel and create a class in CSS with name of that id. See the example below.

#myPanelObj td{
    padding:5px;
},

4) Use renderer to format data in ExtJs grid cell.
If you want to format your data in grid cell use renderer. For example if you are displaying currency in ExtJs grid and you want to append $ sign to it. 
renderer: function(value, cell, record, rowIndex, colIndex, store)
{
          return value + ‘$’;
}
5) Dynamically add event to ExtJs controls. 
Sometimes it may happen that you have to sue some ExtJs controls and you are not allowed to change the control and you need to add some listeners. Following is the code to add listeners dynamically.
myExtJsObj.on(‘hide’,function(){ 
//function body.
});
6) Add Panel Click event
ExtJs panel does not support click event directly. However using following code you can make clickable panel.
listeners: {
                    render: function(p) {                                                                            
                                          p.getEl().on(‘click’, handleProductPanelClick.createDelegate(null, p, true,this.id));
                     }
}
7) Another use of renderer to give style.
You can also use renderer  to give some styles to cells.
renderer: function(value, metaData, r) { 
                  metaData.attr = ‘ style=”color:red;” ‘;
                  return value;
}
This will assign red color to cell.
That’s it for now. I will update this post whenever I will have some more tips.

ExtJs Grid Paging – Go To Last Page After Inserting New Record

Hello,

Recently I was working on a ExtJs editor grid where user can enter new row by pressing button in the top toolbar. A row is inserted at bottom of grid and user can insert data in row. When user tab out or click on Save, the data goes to database and grid store reloaded. See the image below.

Now here is the issue. Consider grid page size as 25 and number of records are 35 and you are on page 1. That means you are viewing record 1 to 25. Now when you insert the row and when grid is refreshed, newly inserted record is in page 2 and you are still on page 1 so sometimes user feels that data is not inserted. So how to overcome this. I will describe solution that I have used. There may be other better solution. If you have any suggestion please add a comment.

First you need to add afteredit event in you grid. See the code below.

listeners:{
            afteredit:function(e){                       
                         Ext.Ajax.request({
                                    url : ‘http://www.example.com/insertData.php’,
                                    method:’GET’,
                                    params:{                                 
                                        id : e.record.id,
                                        value : e.value
                                    },
                                    success:function(resp,opt){                                     
                                    },
                                    failure:function(resp,opt){
                                       
                                    }
                                });
             }
}

When you tab out of editor or Click on Save this event will be fired and it will send data to database using ajax request. Now we all know that for paging in MySql we have to use start and limit. For example.

select * from myTable limit 0,25

Above query will give first 25 records. to fetch next page use following query

select * from myTable limit 25,25

here first 25 indicates first row number of second page. So my trick was to return first row index of last page of table in which new record is inserted. Check the following code.

$start = 25;
$result = $start;

$output[ ‘success’ ] = true;
$output[ ‘result’ ] = $result; 
echo json_encode($output);

Above code will return JSON data back to browser. Now use that to reload the store. Following code will come in Success methods of Ajax Request mentioned in above code.

var returnValue= eval(‘(‘ + resp.responseText + ‘)’);                                  
var start = returnValue.result;
if(start){
              myGrid.store.baseParams.start = start;                                      
}
myGrid.getView().refresh();
myGrid.store.reload();

ExtJs grid store uses start and limit parameter along with paging toolbar. So trick was to set start in base parameters of grid store and reload the grid. This will lead you to the last page in grid after inserting new record so user can see newly added record.