Must see video on Change and Innovation

Making your negative numbers appear red in an Ext grid panel

Making your negative numbers appear red in an Ext grid panel

There are a few ways to make your negative numbers appear red in Ext that use spans that turn your data into text and add a lot of html to your page, this is not one of them. The trick here is to preserve the number format by attaching the class to the existing metadata and returning a properly formatted number. The following renderer will format the number:


function rednegatives(value, metadata) {

metadata.css = (value >= 0) ? "n" : "redCssClass";

return  Ext.util.Format.number(value, "$  0,000.00");

}

The code for the row column should be:


{ id: 'total',  align: 'right', renderer:rednegatives,                sortable:true,    /* This will not work so make sure that the following : xtype:'numbercolumn' is not in your column model  */ summaryType:'sum',dataIndex: 'total',                             sortable:true, header:'Total Price'},

The css code is simple background-color:#330033

Why a sharper stick or a bigger carrot will not make your business faster, smarter, or more productive

If you look at the field of management, most of the core concepts that are still in use today stem from the industrial revolution, when productivity meant automating tasks into simple steps and increases were realized when workers went faster, say producing 20 widgets vs. 50 widgets. In Carnegie’s book How to win Friends and Influence People we were met with the story of two shifts at a factory, and the bosses ingenious way to raise productivity without using a sharp stick or larger carrot.

“To get a factory to produce and meet their quota when they were lagging behind, the big boss asked the day shift how many heats they made. They said “six.” Without another word, he chalked a big “6″ on the floor and walked away. The next day, the boss saw the night shift had rubbed out “6″ and replaced it with a “7.” So, the night shift thought they were better than the day shift, huh? They made 10 that day.”

Yet over 70 years after this passage was written we still seem to be amazed at the fact that this would work better than threats and large cash rewards. Once again everything old is new again.

Cyber War – Richard Clarke discusses the internet and why it will be critical to conflicts of the future.

Your finger is the new mouse, let your users drag and drop data in your web applications!

See the example live here [ http://www.learnsomethings.com/testsomethings/draganddrop/index.php ]

In the near-future drag and drop interactions will gain more importance as more, and more devices that support this behavior come online. Your finger may replace the mouse, we see it in the ipad, and we can see it in the new HP touch screen computer than runs Windows. We have already been trained on how to use this feature by our mobile phones. This means as a web developer you will have to start taking drag and drop seriously, for it will be as intuitive as the checkbox, or the tabbed interface.

Extjs has a drag and drop feature, and some well-documented examples of dragging and dropping objects between grids, grids and forms, or areas in pages created by div tags – but what about dragging to a single cell to update the contents in just that cell? There may be several instances where this would be the preferred method of data entry, in fact any app that contains a list that you pick from and assign to another ‘list’ could be modified to use this method to increase input speed and therefore productivity.

I have set up an example based on something I might like to see in real life, the ability to order a box of crayons that are custom colors, imagine the possibilities, if Crayola could deliver such an app that let users drag colors to their crayon box and place a custom order. You might have corporations design and order boxes that feature their corporate colors like a box in shades of blue for IBM … but I digress, the task at hand is explaining drag and drop using javaScript so your audience can take advantage of the drag and drop features found on mobile devices and tablet computers.

What you will need (let’s start with the Draggable Items) :

Ext.DataView – this will contain a list of procedure codes for the example, formatted much like a datagrid, the formatting of this component is very similar to the sencha touch template

Ext.data.JsonStore – this will contain the data that the DataView will consume

Ext.PagingToolbar – this will be used to page through the records in the DataView

Ext.form.TextField – why not give full text search capability to the store

Ext.dd.DragZone – this will set up the draggable nodes, providing the ability to attach records to the drag handler and remembering where they came from

The Code (Let’s start with the draggable items again)

The block below is nothing special, in fact, it comes straight from the example in the API, in short it receives the mouse down event and places the data in an object so we can access it on mouse release over the target div.  It also remembers where you started so if you decide to release the item somewhere other than a drop area it will slide the div back to that position in the screen.

function initializeColorsDragZone(v) {
   v.dragZone = new Ext.dd.DragZone(v.getEl(), {
//      On receipt of a mousedown event, see if it is within a draggable element.
//      Return a drag data object if so. The data object can contain arbitrary application
//      data, but it should also contain a DOM element in the ddel property to provide
//      a proxy to drag.
        getDragData: function(e) {
            var sourceEl = e.getTarget(v.itemSelector, 10);
            if (sourceEl) {
                d = sourceEl.cloneNode(true);
                d.id = Ext.id();
                return v.dragData = {
                    sourceEl: sourceEl,
                    repairXY: Ext.fly(sourceEl).getXY(),
                    ddel: d,
                    data: v.getRecord(sourceEl).data
                }
            }
        },
//      Provide coordinates for the proxy to slide back to on failed drag.
//      This is the original XY coordinates of the draggable element.
        getRepairXY: function() {
            return this.dragData.repairXY;
        }
    });
}

The next block of code is for the DataView. You may be asking yourself what a data view is right about now, so the short explanation would be a list of items that functions like a data grid and looks similar to the lists that you see on mobile devices, or in Sencha Touch. Our test app will contain a grid of colors in hex code format and a list of selectable colors, not fancy, and might not serve any purpose except for highlighting this functionality. The curly brackets contain the variable that is contained in the store, the classes that are applied to the template could be viewed as pseudo classes in css, for hover, selected, etc.. Finally, the listener calls the function in the block of code above on render.

var ColorsView = new Ext.DataView({
        cls: 'Colors-view',
        tpl: '<tpl for=".">' +
                '<div class="Colors-source"><table><tbody>' +
                    '<tr><td class="Colors-name" style="background-color:{color_code};" ><b>{name}</b></td></tr>' +
                '</tbody></table></div>' +
             '</tpl>',
        itemSelector: 'div.Colors-source',
        overClass: 'Colors-over',
        selectedClass: 'Colors-selected',
        singleSelect: true,
        setAutoScroll:true,
        store: colors_store,
        listeners: {
            render: initializeColorsDragZone
        }
});

On to the store, we will need to set up the colors_store so that the dataView will have data to pull and render in those curly braces above. I’m using an array of colors for the example, but you may want to, wait, you will certainly want to return the data from the database so you would use url: ‘someurl.php’ and return the json string that contains the colors.

First, the array of data.

 var colors = [
        ['#333333',   'Grey'],
        ['#FDFC74',   'Laser Lemon'],
        ['#B2EC5D',   'Inch Worm'],
        ['#B0B7C6',   'Cadet Blue'],
        ['#CDA4DE',   'Wisteria'],
        ['#E3256B',   'Razzmatazz'],
        ['#CB4154',   'Brick Red'],
        ['#A2ADD0',   'Wild Blue Yonder'],
        ['#FDFC74',   'Unmellow Yellow'],
        ['#FFBD88',   'Macaroni and Cheese'],
        ['#FFA089',   'Vivid Tangerine'],
        ['#DEAA88',   'Tumbleweed'],
    ];

And now the store, I know in real life you would probably use a JSON store but this sis just an example and I did not want to build a database application.

var colors_store = new Ext.data.ArrayStore({
 fields: [
   {name: 'hexcode',   type: 'string'},
   {name: 'name',        type: 'string'}
  ]
});
 colors_store.loadData(colors);

Now for the paging toolbar just to illustrate that the data view widget may be used much like the grid.

var colors_bbar = new Ext.PagingToolbar({
  id:'colors_bbar',
  pageSize: 25,
  store: colors_store,
  displayInfo: true,
  displayMsg: '{0} - {1} of {2}',
  emptyMsg: "No colors to display"
});

Now on to the drop targets, which of course will be cells in a table that will hold three colors. When you drag a column over from the data view on the left it should replace the contents of the cell with the selected color.

What you will need ( on to the drop zones!) :

Ext.grid.GridPanel – this will contain 10 rows that will hold the drop zones for the colors in the dataView

Ext.dd.DropZone – this will contain 10 rows that will hold the drop zones for the colors in the dataView

First, the drop zone code, this is where all of the magic takes place as it will hold the old values, new values, and the code to make the data switch.

function initializeOrgDropZone(g) {
    g.dropZone = new Ext.dd.DropZone(g.getView().scroller, {

//      If the mouse is over a target node, return that node. This is
//      provided as the "target" parameter in all "onNodeXXXX" node event handling functions
        getTargetFromEvent: function(e) {
            return e.getTarget('.color-target');
        },

//      On entry into a target node, highlight that node.
        onNodeEnter : function(target, dd, e, data){
            Ext.fly(target).addClass('color-target-hover');
        },

//      On exit from a target node, unhighlight that node.
        onNodeOut : function(target, dd, e, data){
            Ext.fly(target).removeClass('color-target-hover');
        },

//      While over a target node, return the default drop allowed class which
//      places a "tick" icon into the drag proxy.
        onNodeOver : function(target, dd, e, data){
            return Ext.dd.DropZone.prototype.dropAllowed;
        },

//      On node drop, we can interrogate the target node to find the underlying
//      application object that is the real target of the dragged data.
//      In this case, it is a Record in the GridPanel's Store.
//      We can use the data set up by the DragZone's getDragData method to read
//      any data we decided to attach.
        onNodeDrop : function(target, dd, e, data){
            var rowIndex = g.getView().findRowIndex(target);
            var colIndex = g.getView().findCellIndex(target);
            var h = g.getStore().getAt(rowIndex);

   var targetEl = Ext.get(target);

            targetEl.update('<div class="color-target" id="'+targetEl.id + '" style="background-color:'+  data.data.hexcode + '" > '+  data.data.name   + ' </div>'   );

            return true;
        }
    });
}

Now we will need the grid that contains the drop zones. There are a few things that you should note when setting this grid up; enableColumnMove has been set to false to disallow the user from reordering the last three color columns, if this was to happen the column index would not map to the correct columns and would throw off the drop functions logic. Hideable has been set to false to disallow the user from hiding any of the columns that come before the color columns, as this too would throw off the column ids. We also need the ‘crayon boxes’ that the users will fill, and a store that is connected to the boxes. The renderer will place a div in the empty crayon cells that will serve as a drop zone for the crayons.


var crayon_box = [
        ['1',   'Box One', '','','','','','','',''],
        ['2',   'Box Two', '','','','','','','',''],
        ['3',   'Box Three', '','','','','','','',''],
        ['4',   'Box Four', '','','','','','','',''],
        ['5',   'Box Five', '','','','','','','',''],
        ['6',   'Box Six', '','','','','','','',''],
        ['7',   'Box Seven', '','','','','','','',''],
        ['8',   'Box Eight', '','','','','','','','']
    ];

var crayon_box_store = new Ext.data.ArrayStore({
 fields: [
   {name: 'rid',   type: 'string'},
   {name: 'name',        type: 'string'},
   {name: 'first_color',        type: 'string'},
   {name: 'second_color',        type: 'string'},
   {name: 'third_color',        type: 'string'},
   {name: 'fourth_color',        type: 'string'},
   {name: 'fifth_color',        type: 'string'},
   {name: 'sixth_color',        type: 'string'},
   {name: 'seventh_color',        type: 'string'},
   {name: 'eighth_color',        type: 'string'}
  ]
});
crayon_box_store.loadData(crayon_box);

function fcolor(value, p, record, rowIndex, colIndex, store){

 return '<div class="user-target" style="height:12px" id="4"> '+ value + '  </div>';

}

var colors_grid = new Ext.grid.GridPanel({
  region:'center',
  loadMask :true,
  stateful:false,
  enableColumnMove:false,
  store: colors_grid_store,
  title: ' An List to Cell Drag and Drop Example - Go ahead drag a color from the left to the Colors columns below! ',
  id:'color_grid',
  stripeRows:true,
  margins: '0 5 0 0',
  columnLines:true,
  columns: [
   { header: 'Row Id', dataIndex: 'rid', width: 100,hidden:false,hideable:false },
   { header: 'Name',   dataIndex: 'name', width: 70,sortable: true ,hideable:false },
   { header: 'First Color', renderer:fcolor, dataIndex: 'first_color',width: 155, hidden:false,hideable:false },
   { header: 'Second Color',  renderer:scolor, dataIndex: 'second_color', width: 155,sortable: true,hideable:false },
   { header: 'Third Color',  renderer:tcolor, dataIndex: 'third_color', width: 155,sortable: true,hideable:false }
        ],
  listeners: {
            render: initializeOrgDropZone
        }
});

Last but not least we stuff all this in a viewport.

var MyViewportUi = new Ext.Viewport({
    layout: 'border',
    id: 'colorsSample',
    border:false,
    items: [{
            title: 'Colors',
            region: 'west',
            bbar:colors_bbar,
            xtype:'panel',
            width: 300,
             autoScroll:true,

            items:  [ColorsView
            ]},
            colors_grid
            ]
});