RESTful store example as a pre-configured class

| | Comments (2)

The ExtJS 3.2+ examples include a “RESTful store” which is a very interesting no-code way to get full CRUD behaviour from a GridPanel. Unfortunately the example is not written with a reusable structure - here is the same example, but as a pre-configured class:


Ext.onReady(function() {
            Ext.QuickTips.init();

            var TheGrid = Ext.extend(Ext.grid.GridPanel, {
                        title: 'Users',
                        frame: true,
                        height: 300,
                        width: 500,
                        viewConfig: {
                            forceFit: true
                        },
                        editor: new Ext.ux.grid.RowEditor({
                                    saveText: 'Update'
                                }),


                        onAdd: function(btn, ev) {
                            var u = new this.store.recordType({
                                        first: '',
                                        last: '',
                                        email: ''
                                    });
                            this.editor.stopEditing();
                            this.store.insert(0, u);
                            this.editor.startEditing(0);
                        },


                        onDelete: function() {
                            var rec = this.getSelectionModel().getSelected();
                            if (rec) {
                                this.store.remove(rec);
                            }
                        },


                        initComponent: function() {
                            var proxy = new Ext.data.HttpProxy({
                                        url: 'app.php/users'
                                    });

                            var reader = new Ext.data.JsonReader({
                                        totalProperty: 'total',
                                        successProperty: 'success',
                                        idProperty: 'id',
                                        root: 'data',
                                        messageProperty: 'message' // attribute in server response for user message...
                                    }, [{
                                                name: 'id'
                                            }, {
                                                name: 'email'
                                            }, {
                                                name: 'first',
                                                allowBlank: false
                                            }, {
                                                name: 'last'
                                            }]);

                            var writer = new Ext.data.JsonWriter({
                                        encode: false
                                    });

                            var store = new Ext.data.Store({
                                        restful: true,
                                        proxy: proxy,
                                        reader: reader,
                                        writer: writer
                                    });

                            var config = {
                                store: store,
                                plugins: [this.editor],
                                columns: [{
                                            header: "ID",
                                            width: 40,
                                            sortable: true,
                                            dataIndex: 'id'
                                        }, {
                                            header: "Email",
                                            width: 100,
                                            sortable: true,
                                            dataIndex: 'email',
                                            editor: new Ext.form.TextField({})
                                        }, {
                                            header: "First",
                                            width: 50,
                                            sortable: true,
                                            dataIndex: 'first',
                                            editor: new Ext.form.TextField({})
                                        }, {
                                            header: "Last",
                                            width: 50,
                                            sortable: true,
                                            dataIndex: 'last',
                                            editor: new Ext.form.TextField({})
                                        }],
                                tbar: [{
                                            text: 'Add',
                                            iconCls: 'silk-add',
                                            handler: this.onAdd,
                                            scope: this
                                        }, '-', {
                                            text: 'Delete',
                                            iconCls: 'silk-delete',
                                            handler: this.onDelete,
                                            scope: this
                                        }, '-']
                            };

                            Ext.apply(this, Ext.apply(this.initialConfig, config));
                            TheGrid.superclass.initComponent.apply(this, arguments);

                        },


                        onRender: function() {
                            this.store.load();
                            TheGrid.superclass.onRender.apply(this, arguments);
                        }
                    });
            Ext.reg('my_grid', TheGrid);



            var w = new Ext.Window({
                        modal: true,
                        items: {
                            xtype: 'my_grid',
                            title: 'Panel 1'
                        }
                    });
            w.show();
        });


Using the 'ref' option in ExtJS 3.x

| | Comments (0)

As with so many things in ExtJS, the ‘ref’ option introduced in 3.0 is not very well documented, at least as far as I can tell. Which is unfortunate, because it’s extremely useful, and drastically reduces the need for ids. Here’s an example of how to use it:

Ext.onReady(function() {
            Ext.BLANK_IMAGE_URL = 'ext/resources/images/default/s.gif';
            Ext.QuickTips.init();


            // Define a simple component

            MyComponent = Ext.extend(Ext.form.FormPanel, {
                        frame: true,

                        initComponent: function() {
                            var config = {
                                items: [{
                                            xtype: 'textfield',
                                            fieldLabel: 'Name'
                                        }, {
                                            xtype: 'textfield',
                                            fieldLabel: 'Address'
                                        }],
                                bbar: ['->', {
                                            text: 'Cancel',
                                            minWidth: 100,
                                            ref: '../cancelButton' 
                                        }, {
                                            text: 'Save',
                                            minWidth: 100,
                                            ref: '../saveButton' 
                                        }]
                            };

                            Ext.apply(this, Ext.apply(this.initialConfig, config));
                            MyComponent.superclass.initComponent.apply(this, arguments);

                        }
                    });
            Ext.reg('my_component_xtype', MyComponent);


            // Create a display a window with the panel in it...

            var w = new Ext.Window({
                        modal: true,
                        items: {
                            xtype: 'my_component_xtype',
                            title: 'Panel 1',
                            ref: 'theFormPanel'
                        }
                    });
            w.show();


            // See how we can use the references...

            w.theFormPanel.saveButton.on('click', function() {
                        console.log('Save was clicked');
                    }, this);

            console.log(w.theFormPanel.title);
        });

Drupal - adding metadata to FileField

| | Comments (0)

While working with file uploads in Drupal, I had a situation where I needed to be able to attach metadata to FileFields. Specifically, the site needed to support video uploads, with a low-res Flash video that would be uploaded via Drupal. For each of these Flash videos, there would be a corresponding high-res broadcast video that would be hosted on an external server, and that would be made available to the user via a URL. So, I needed to be able to attach a “download URL” as metadata to each FileField. I wanted my upload form to look like this:

filefield_metadata.jpg


A few hours of Google searching led me to think that this was a pretty complex task - this page for instance is a detailed description of how to solve the problem, via the creation of a compound CCK field.

However, it turns out that there is a simpler solution, as described on the Trellon blog. Below is my description of how I solved the problem using the same technique.

The first thing you need to do is create your own Drupal module - this is very simple, and involves creating a folder in the “/sites/all/modules/” folder. My module is called “mediacentre”, so I created “/sites/all/modules/mediacentre/”, and in that folder I created two files - “mediacentre.info” and “mediacentre.module”.

Here is the “mediacentre.info” file:

    ; $Id: 
    name = Media Centre
    description = Media Centre
    core = 6.x



The “mediacentre.module” file is a little more complex:

<?php
function mediacentre_form_alter(&$form, $form_state, $form_id) {
    if ($form_id == "story_node_form") {

        // each field can have multiple values, we need to add custom process function to every upload field
        foreach (element_children($form['field_video']) as $key) {
            $type = $form['field_video'][$key]['#type'];

            if ($type == 'filefield_widget') {
                $a = array('filefield_widget_process', 'download_url_widget_process');
                $form['field_video'][$key]['#process'] = $a;

                $va = array('filefield_widget_validate', 'download_url_widget_validate');
                $form['field_video'][$key]['#element_validate'] = $va;
            }
        }
    }
}

function download_url_widget_process($element, $edit, &$form_state, $form) {
    $file = $element['#value'];

    $element['data']['download'] = array(
        '#type' => 'textfield',
        '#title' => t('Download URL'),
        '#value' => $file['fid'] ? $file['data']['download'] : ''
    );

    return $element;
}

function download_url_widget_validate($element, &$form_state) {
}


In the above code the important method is “mediacentre_form_alter” - this is a Drupal form hook - the Drupal FAPI documentation has much more information on this, most of it horribly confusing if you’re just trying - like I was - to learn the basics. With the above method in our module, every time Drupal displays a form it will call our form hook, so we can customize the form as needed.

In the form hook method we check for the ID of the form we want to modify - this can be discovered by using Firebug or the Webkit Inspector to examine your page. In my case, I wanted to modify the Drupal form for editing nodes, and I was looking specifically for the forms that were used to upload my videos. I was using CCK for these fields, and the field name was “field_video”. If you use a different field name, then you have to change the use of ‘field_video’ in the method to the name of your own field.

For each ‘field_video’, we check for the ‘filefield_widget’, which is the actual upload form we want to modify, and we replace the existing ‘#process’ key for that array with a new value that includes the name of our “process” or “validate” method.

So, when Drupal displays the “filefield_widget”, it will now call our “download_url_widget_process” method, and that method will insert a new element into the form with the name ‘download’, and the title ‘Download URL’.

Right now we’re not doing any particular validation, so we just leave the “download_url_widget_validate” method blank. Normally this method would contain code to make sure that the value entered is OK.

And that’s it! When displaying your data in a tpl.php you have access to the new “download” value, in the same way you would access the “description” value, as a key in the item->data array.


There’s a customized version of Firebug available called Widerbug that changes the Firebug layout to look like this:

ScreenCapture001.jpg



Unfortunately Widerbug is not updated as frequently as Firebug, so if you want to use the most recent versions of Firebug you’re out of luck.

To solve this issue I used FileMerge to compare Widerbug with a stock release of Firebug, and came up with the following list of required changes: (UPDATE: It turns out that in the Widerbug xpi there’s a text file “instructions.txt” that details these steps as well… ha! Note that the steps described in the Widerbug “instructions.txt” are slightly more complex than mine, as they involve changing some Firebug artwork, the update URL, and signing the XPI.)

Anyway, here are my changes for Firebug 1.5.0. We edit the relevant files in-place, after Firebug has been installed. First you need to open the Firefox “Profiles” directory, which on OS X is located at ~/Library/Application Support/Firefox/Profiles - open the appropriate profile, then look for the “extensions” directory, and inside that is the “firebug@software.joehewitt.com” directory. Make the following edits:


1) content/firebug/browserOverlay.xul

Replace this:

    <vbox id="appcontent">
        <splitter id="fbContentSplitter" collapsed="true"/>
        <vbox id="fbContentBox" collapsed="true" persist="height"></vbox>
    </vbox>

With this:

    <hbox id="browser">
        <splitter id="fbContentSplitter"/>
        <vbox id="fbContentBox" flex="1" collapsed="true" persist="width"/>
    </hbox>



2) content/firebug/firebugOverlay.xul

Change line 141 from

    <box id="fbPanelPane" flex="1" persist="orient">

to

    <vbox id="fbPanelPane" flex="1" persist="orient">



and change line 276, the corresponding closing tag, from

    </box>

to

    </vbox>



3) content/firebug/firebug.css

Insert this:

    #fbToolbox {
        border-top-width: 0px;
        border-top-style: none;
    }

Before this:

    /************************************************************************************************/
    panelTabMenu {
        -moz-binding: url("chrome://firebug/content/bindings.xml#panelTabMenu");
    }



4) skin/classic/mac/firebug.css

Replace this:

    #fbContentSplitter {
        border-top: 1px solid #BBB9BA;
        border-bottom: none;
        background: #f3f3f3 !important;
        min-height: 3px;
        max-height: 3px;
    }

With this:

    #fbContentSplitter {
        border-left: 1px solid #BBB9BA;
        border-right: 1px solid #BBB9BA;
        background: #f3f3f3 !important;
        min-width: 5px;
        max-width: 5px;
    }



4) skin/classic/win/firebug.css

Replace this:

    #fbContentSplitter {
        border-top: 1px solid !important;
        -moz-border-top-colors: threedShadow !important;
        border-bottom: 1px solid !important;
        -moz-border-bottom-colors: #EEEEEE !important;
        min-height: 3px;
        max-height: 3px;
        background-color: #FFFFFF;
    }

With this:

    #fbContentSplitter {
        border-left: 1px solid !important;
        -moz-border-left-colors: threedShadow !important;
        border-right: 1px solid !important;
        -moz-border-right-colors: threedShadow !important;
        min-width: 3px;
        max-width: 3px;
        background-color: #d4d0c8;
    }



NOTE: The next time you update Firebug these changes will - of course - be overridden by the new version. So it’s pretty ugly, but it works.

Enabling event bubbling for all items in a class

| | Comments (0)

There doesn't seem to be direct way in ExtJS to indicate that all items in a class should bubble events. Below is simple workaround - we iterate over all the items in the class in the 'afterRender' event:


Ext.BLANK_IMAGE_URL = 'lib/ext/resources/images/default/s.gif';

Ext.onReady(function() {
        Ext.QuickTips.init();


        FP = Ext.extend(Ext.form.FormPanel, {
                    frame: true,

                    initComponent: function() {
                        var config = {
                            items: [{
                                        xtype: 'textfield',
                                        name: 'First',
                                        fieldLabel: 'First'
                                    }, {
                                        xtype: 'textfield',
                                        name: 'Second',
                                        fieldLabel: 'Second'
                                    }]
                        };

                        Ext.apply(this, Ext.apply(this.initialConfig, config));
                        FP.superclass.initComponent.apply(this, arguments);

                        this.on('change', function(field, newVal, oldVal) {
                                    console.log('form change event on ' + field.name);
                                }, this);
                    },


                    // When the form has been rendered, we step though all the items on 
                    // the form and enable bubbling for each one. In a more complex form
                    // we would need to check the type of each item and enable the right
                    // kind of events, of course.

                    afterRender: function() {
                        FP.superclass.afterRender.apply(this, arguments);
                        Ext.each(this.items.items, function(item) {
                                    item.enableBubble('change');
                                }, this);
                    }
                });


        var fp = new FP();
        var win = new Ext.Window({
                    items: [fp]
                });
        win.show();
    });

Complex objects in classes

| | Comments (0)


When using Ext.extend to create your own classes, it's critical to understand that complex objects defined outside of a function definition are added to the prototype of the extended class, and as such are shared across all instances of the class. This sharing is not the case with simple attributes.

The solution is to define complex objects inside the "initComponent" function, referencing them via "this".



Ext.BLANK_IMAGE_URL = 'lib/ext/resources/images/default/s.gif';

Ext.onReady(function() {
        Ext.QuickTips.init();

    // This class definition is broken for most uses - the 'obj' complex object is 
    // created when the class is defined, and as such is shared across all instances
    // of the class! Confusingly, 'simple' class attributes are /not/ shared.

        BrokenClass = Ext.extend(Ext.Panel, {
                    obj: {
                        colour: 'red'
                    },
                    simple: 'one', // this is not shared

                    initComponent: function() {
                        BrokenClass.superclass.initComponent.apply(this, arguments);
                    }
                });


    // This class definition is not broken - the 'obj' complex object is created when an 
    // instance of the class is created, and thus is unique to each instance.

        WorkingClass = Ext.extend(Ext.Panel, {
                    initComponent: function() {
                        this.obj = {
                            colour: 'red'
                        };
                        WorkingClass.superclass.initComponent.apply(this, arguments);
                    }
                });



    // Note that b1 and b2 share the value of 'obj', but do NOT share the value 
    // of 'simple'

        var b1 = new BrokenClass();
        var b2 = new BrokenClass();

        b2.obj.colour = 'blue';
        b2.simple = 'two';

        console.log(b1.obj.colour, b2.obj.colour, b1.simple, b2.simple);


        // Note that w1 and w2 each have their own values for 'obj'

        var w1 = new WorkingClass();
        var w2 = new WorkingClass();

        w1.obj.colour = 'blue';

        console.log(w1.obj.colour, w2.obj.colour);
    });

GridPanel from JSON data

| | Comments (0) | TrackBacks (0)



Given the following JSON data:

{"totalCount": 2,"items": [{"ID": 1,"Name": "First"},{"ID": 2,"Name": "Second"}]}


Note: ExtJS requires the above format for GridPanel data. The list of data must be wrapped in an object that contains a "total count" attribute, and the list itself is the data of an "items" attribute. These names of these attributes must match the "totalProperty" and "root" values in the JsonReader of the Store used by the GridPanel. See below.




Here's an ExtJS GridPanel that will load and display it:

ExampleGrid = Ext.extend(Ext.grid.GridPanel, { title: 'Example', border: true, frame: true, closable: true,

        initComponent: function() {

            var proxy = new Ext.data.HttpProxy({
                        url: 'http://host/url/to/get/JSON/data'
                    });

            var store = new Ext.data.Store({
                        remoteSort: true,
                        proxy: proxy,
                        baseParams: {
                            limit: 100
                        },
                        reader: new Ext.data.JsonReader({
                                    totalProperty: 'totalCount',
                                    root: 'items'
                                }, [{
                                            name: 'ID'
                                        }, {
                                            name: 'Name'
                                        }])
                    });

            Ext.apply(this, {
                        loadMask: true,
                        store: store,
                        colModel: new Ext.grid.ColumnModel([{
                                    header: 'ID',
                                    dataIndex: 'ID',
                                    sortable: true
                                }, {
                                    header: 'Name',
                                    dataIndex: 'Name',
                                    sortable: true
                                }])
                    });

            ExampleGrid.superclass.initComponent.apply(this, arguments);
        },

        onRender: function() {
            this.store.load();
            ExampleGrid.superclass.onRender.apply(this, arguments);
        }
    });

Ext.reg('ExampleGrid_panel', ExampleGrid);

Creating a TreePanel from markup

| | Comments (0)



Here's an example of how to create an ExtJS TreePanel from markup. Note the use of "AsyncTreeNode" and "TreeLoader" - even though this is a statically-marked up tree, it will not work without those configuration options. I don't know if this is a lack of understanding on my part or not, but the code below works. :)



Ext.BLANK_IMAGE_URL = 'lib/ext/resources/images/default/s.gif';

Ext.onReady(function(){
    Ext.QuickTips.init();


    // Create the "SampleTreePanel" pre-configured class

    SampleTreePanel = Ext.extend(Ext.tree.TreePanel, {
        title: 'Sample Tree Panel',
        width: 200,
        height: 400,
        loader: new Ext.tree.TreeLoader(),
        rootVisible: false,
        border: false,

        initComponent: function(){
            Ext.apply(this, {

                root: new Ext.tree.AsyncTreeNode({
                    children: [{
                        text: 'First',
                        expanded: true,
                        children: [{
                            text: 'one',
                            leaf: true
                        }, {
                            text: 'two',
                            leaf: true
                        }]
                    }, {
                        text: 'Second',
                        expanded: true,
                        children: [{
                            text: 'one',
                            leaf: true
                        }]
                    }]
                })
            })

            SampleTreePanel.superclass.initComponent.apply(this, arguments);
        }
    });
    Ext.reg('tree_panel', SampleTreePanel);


    // Instantiate the tree panel, then attach an event listener..

    var tree = new SampleTreePanel();

    tree.on('click', function(node, e){
        debugger;
    }, this);



    // And create a window to display the tree panel in...

    var wind = new Ext.Window({
        plain: true,
        bodyStyle: 'padding:5px;',
        layout: 'fit',
        items: [tree]
    });

    wind.show();
});

Embedding a FormPanel in another FormPanel

| | Comments (2)

Often I want to create a pre-configured class to encapsulate some form fields in a reusable way. When doing this, however, you cannot extent Ext.FormPanel - if you do this and then try to embed your class in an existing FormPanel you’ll get an obscure error deep in the bowels of ExtJS. :(

Instead, extend Ext.Panel, and then create a FormPanel inside your panel. For example, here’s a simple “LocationPanel” that displays a Campus and Building labels. Note that the class extends Ext.Panel, and then embeds a ‘form’ xtype, and the form fields are inside that…

    LocationPanel = Ext.extend(Ext.Panel, {
        campus: 'defaultCampus',
        building: 'defaultBuilding',

        width: 300,
        height: 50,
        frame: true,
        border: true,
        labelWidth: 75,
        title: 'Location Panel',

        initComponent: function(){
            Ext.apply(this, {
                items: [{
                layout: 'form',
                    items: [{
                        layout: 'column',
                        items: [{
                            columnWidth: '.5',
                            layout: 'form',
                            items: [{
                                    xtype: 'label',
                                    text: this.campus
                            }]
                        }, {
                            columnWidth: '.5',
                            layout: 'form',
                            items: [{
                                    xtype: 'label',
                                    text: this.building
                            }]
                        }]
                    }]
                }]
            });
            LocationPanel.superclass.initComponent.apply(this, arguments);
        }
    });
    Ext.reg('location_panel', LocationPanel);

Classes with custom events

| | Comments (0)


Here’s an example of a pre-configured class that fires a custom event, and code that then listens for the event:


Ext.BLANK_IMAGE_URL = 'lib/ext/resources/images/default/s.gif';

Ext.onReady(function(){
    Ext.QuickTips.init();

    MyForm = Ext.extend(Ext.form.FormPanel, {
        id: 'simpleForm',
        title: 'Simple Form',
        frame: true,
        width: 300,
        initComponent: function(){
            Ext.apply(this, {
                renderTo: Ext.getBody(),
                items: [new Ext.Button({
                    id: 'theButton',
                    text: 'Test',
                    listeners: {
                        'click': {

                        // this 'scope' value is CRITICAL so that the event is fired in 
                        // the scope of the component, not the anonymous function...

                            scope: this,        

                            fn: function(field, newVal, oldVal){
                                console.log("custom_event fired");
                                this.fireEvent('custom_event');
                            }
                        }
                    }
                })]
            });
            MyForm.superclass.initComponent.apply(this, arguments);


          // This 'addEvents' call does not seem to be technically required, but most 
          // of the ExtJS examples use it, and it provides a good way of documenting 
          // which events your class fires.

            this.addEvents('custom_event');
        }
    });




    // Create an instance of the form, and listen for the event...

    var simple = new MyForm({});

    simple.on('custom_event', function(){
        console.log("custom event received!");
    });
});