Ext.ux.grid.Editor

Publicado por EVERTON DA ROSA (última atualização em 02/02/2011)

[ Hits: 4.616 ]

Homepage: http://everton3x.github.io

Download veiculos3.zip




Ext.ux.grid.Editor é uma extensão da classe Ext.grid.EditorGridPanel, do framework ExtJS que oferece ao usuário um grid (tabela) com paginação e ordenação de colunas, adição, exclusão e modificação de registros.

As operações CRUD (Create, Read, Update, Delete) podem ser realizadas através da edição direta nas linhas do grid ou através de formulário (bastando passar a configuração editForm para ativar os formulários).

Este é uma user extension para quem conhece um pouco de ExtJS. Embora esteja em estágio Alfa, pode tranquilamente ser utilizada.

  



Esconder código-fonte

Ext.ns('Ext.ux.grid');
Ext.ux.grid.Editor = Ext.extend(Ext.grid.EditorGridPanel, {
    autoHeight: true
    ,border: false
    ,sm: new Ext.grid.CellSelectionModel({
        singleSelect:true
    })
    ,loadMask: new Ext.LoadMask(Ext.getBody(),{
        msg: 'Lendo dados no servidor ...'
        ,removeMask: true
    })
    ,stripeRows: true
    ,maskDisabled: true
    ,initComponent: function(){
        this.viewConfig = {
            forceFit: true
            ,emptyText: 'Sem registros para exibir!'
        };

        this.store.autoDestroy = true;
        this.store.autoLoad = true;
        this.store.autoSave = false;
        this.store.remoteSort = false;
        this.store.writer = new Ext.data.JsonWriter({
            encode: true
            ,writeAllFields: true
        });
        this.store.reader = new Ext.data.JsonReader({
            successProperty: 'success'
            ,messageProperty: 'message'
            ,totalProperty: 'total'
        });
        this.store.baseParams = {
            start: 0
            ,limit: Ext.PAGESIZE
        };


        this.store.waitMsg = 'Salvando registro ...';
        this.store.waitTitle = 'Aguarde ...';

        this.store = new Ext.data.JsonStore(this.store);

        this.tbar = new Ext.Toolbar({
            items: [{
                    text: 'Novo'
                    ,iconCls: 'x-icon-add'
                    ,handler: this.onAdd
                    ,scope: this
            },{
                    text: 'Salvar'
                    ,id: 'btn-save'
                    ,iconCls: 'x-icon-save'
                    ,disabled: true
                    ,handler: this.onSave
                    ,scope: this
            },{
                    text: 'Editar'
                    ,id: 'btn-edit'
                    ,iconCls: 'x-icon-edit'
                    ,handler: this.onEdit
                    ,scope: this
                    ,disabled: true
            },{
                    text: 'Apagar'
                    ,id: 'btn-delete'
                    ,iconCls: 'x-icon-delete'
                    ,handler: this.onDestroy
                    ,scope: this
                    ,disabled: true
            },{
                    text: 'Cancelar'
                    ,id: 'btn-cancel'
                    ,iconCls: 'x-icon-cancel'
                    ,handler: this.onCancel
                    ,scope: this
                    ,disabled: true
            }]
        });
        this.bbar = new Ext.PagingToolbar({
            pageSize: Ext.PAGESIZE
            ,store: this.store
            ,displayInfo: true
            ,afterPageText: 'de {0}'
            ,beforePageText: 'Página'
            ,firstText: 'Primeira página'
            ,lastText: 'Última página'
            ,nextText: 'Próxima página'
            ,prevText: 'Página anterior'
            ,refreshText: 'Atualizar'
            ,displayMsg: 'Mostrando registros {0} a {1} do total de {2}'
            ,emptyMsg: 'Sem registros para exibir'
        });

        Ext.ux.grid.Editor.superclass.initComponent.call(this);

        Ext.TITLEDEFAULT = this.title;
        Ext.ICONCLSDEFAULT = this.iconCls;

        this.success = true;
        this.error = new Array();

        this.addListener('rowdblclick', function(){
            this.onEdit();
        }, this);

        this.addListener('cellclick', function(){
            this.enableBtnEdit();
            this.enableBtnDelete();
        }, this);

        this.store.addListener('save', function(str){
            this.setTitle(Ext.TITLEDEFAULT);
            this.setIconClass(Ext.ICONCLSDEFAULT);

            if(this.success === false){
                Ext.Msg.show({
                    title: 'Erro ao salvar'
                    ,msg: this.error
                    ,buttons: Ext.Msg.OK
                    ,icon: Ext.Msg.ERROR
                });
            }else{
                Ext.Msg.show({
                    title: 'Sucesso ao salvar'
                    ,msg: 'Registros salvos com sucesso!'
                    ,buttons: Ext.Msg.OK
                    ,icon: Ext.Msg.INFO
                });
                this.store.reload();
            }
        }, this);

        this.store.addListener('exception', function(proxy, type, action, options, response, arg){
            if(type == 'remote'){
                if(response.raw.read === true){
                    Ext.Msg.show({
                        title: 'Erro ao ler dados'
                        ,msg: response.raw.message
                        ,buttons: Ext.Msg.OK
                        ,icon: Ext.Msg.ERROR
                    });
                }else{
                    this.error += response.raw.message;
                    this.success = false;
                }

            }else if(type == 'response'){
                var res = Ext.util.JSON.decode(response.responseText);

                if(res.read === true){
                    Ext.Msg.show({
                        title: 'Erro ao ler dados'
                        ,msg: res.message
                        ,buttons: Ext.Msg.OK
                        ,icon: Ext.Msg.ERROR
                    });
                }else{
                    if(res.success === false){
                        this.error += res.message;
                        this.success = false;
                    }
                }
            }
        }, this);

        this.store.addListener('write', function(proxy, action, data, response, record, options){
            if(response.raw.success === false){
                this.error += response.raw.message;
                this.success = false;
            }
        }, this);

    }
    ,showError: function(){
        
    }
    ,onAdd: function(btn, ev){
        if(this.editForm){
            this.createInForm();
        }else{
            this.createInLine();
        }
    }
    ,createInLine: function(){
        this.setTitle(Ext.TITLEDEFAULT + ' [MODIFICADO]');
        this.setIconClass('x-icon-edit');
        var u = new this.store.recordType();
        this.stopEditing();
        this.store.insert(0, u);
        this.startEditing(0,1);
        this.enableBtnSave();
        this.enableBtnCancel();
    }
    ,createInForm: function(){
        this.setTitle(Ext.TITLEDEFAULT + ' [MODIFICADO]');
        this.setIconClass('x-icon-edit');
        this.disable();
        this.stopEditing();
        var form = this.createForm(this.editForm, 'create');
        
        var win = new Ext.Window({
            title: 'Adição de registro'
            ,iconCls: 'x-icon-add'
        });
        win.add(form);
        win.show();

        win.addListener('beforeclose', function(panel){
            this.store.reload();
            this.enable();
        }, this);
    }
    ,onEdit: function(btn, ev){
        if(this.getSelectionModel().hasSelection()){
            if(this.editForm){
                this.editInForm(this);
            }else{
                this.editInLine(this);
            }
        }else{
            Ext.Msg.show({
                title: 'Erro na edição'
                ,msg: 'Não há nenhum registro selecionado!'
                ,buttons: Ext.Msg.OK
                ,icon: Ext.MessageBox.ERROR
            });
        }
    }
    ,onSave: function(btn, ev){
        this.disableBtnSave();
        this.disableBtnEdit();
        this.disableBtnDelete();
        this.disableBtnCancel();
        this.store.save();
    }
    ,onDestroy: function(){
        var index = this.getSelectionModel().getSelectedCell();
        if(!index){
            Ext.Msg.show({
                title: 'Erro na exclusão'
                ,msg: 'Não há nenhum registro selecionado!'
                ,buttons: Ext.Msg.OK
                ,icon: Ext.MessageBox.ERROR
            });
        }else{
            this.enableBtnSave();
            this.enableBtnCancel();
            var rec = this.store.getAt(index[0]);
            this.store.remove(rec);
        }
    }
    ,onCancel: function(btn, ev){
        this.setTitle(Ext.TITLEDEFAULT);
        this.setIconClass(Ext.ICONCLSDEFAULT);
        this.store.rejectChanges();
        this.disableBtnSave();
        this.disableBtnEdit();
        this.disableBtnDelete();
        this.disableBtnCancel();
    }
    ,enableBtnSave: function(){
        var tbar = this.getTopToolbar();
        var btn = tbar.get('btn-save');
        btn.setDisabled(false);
    }
    ,disableBtnSave: function(){
        var tbar = this.getTopToolbar();
        var btn = tbar.get('btn-save');
        btn.setDisabled(true);
    }
    ,enableBtnEdit: function(){
        var tbar = this.getTopToolbar();
        var btn = tbar.get('btn-edit');
        btn.setDisabled(false);
    }
    ,disableBtnEdit: function(){
        var tbar = this.getTopToolbar();
        var btn = tbar.get('btn-edit');
        btn.setDisabled(true);
    }
    ,enableBtnDelete: function(){
        var tbar = this.getTopToolbar();
        var btn = tbar.get('btn-delete');
        btn.setDisabled(false);
    }
    ,disableBtnDelete: function(){
        var tbar = this.getTopToolbar();
        var btn = tbar.get('btn-delete');
        btn.setDisabled(true);
    }
    ,enableBtnCancel: function(){
        var tbar = this.getTopToolbar();
        var btn = tbar.get('btn-cancel');
        btn.setDisabled(false);
    }
    ,disableBtnCancel: function(){
        var tbar = this.getTopToolbar();
        var btn = tbar.get('btn-cancel');
        btn.setDisabled(true);
    }
    ,editInLine: function(){
        this.setTitle(Ext.TITLEDEFAULT + ' [MODIFICADO]');
        this.setIconClass('x-icon-edit');
        this.enableBtnSave();
        this.enableBtnEdit();
        this.enableBtnCancel();
        var rec = this.getSelectionModel().getSelectedCell();
        this.startEditing(rec[0], rec[1]);
    }
    ,editInForm: function(){
        this.setTitle(Ext.TITLEDEFAULT + ' [MODIFICADO]');
        this.setIconClass('x-icon-edit');
        this.disable();
        this.stopEditing();
        var form = this.createForm(this.editForm, 'update');
        var rec = this.getSelectionModel().getSelectedCell();
        var row = rec[0];
        var record = this.store.getAt(row);
        form.getForm().loadRecord(record);
        
        var win = new Ext.Window({
            title: 'Edição de registro'
            ,iconCls: 'x-icon-edit'
        });
        win.add(form);
        win.show();

        win.addListener('beforeclose', function(panel){
            this.store.reload();
            this.enable();
        }, this);

    }
    ,createForm: function(fields, action){
        var form = new Ext.form.FormPanel({
            border: false
            ,id: 'edit-form'
            ,bodyStyle:'padding:5px 5px 5px 5px'
            ,url: this.store.url
            ,items: fields
            ,buttons: [{
                    text: 'Salvar'
                    ,iconCls: 'x-icon-save'
                    ,handler: function(){
                        var el = Ext.ComponentMgr.get('edit-form');
                        el.getForm().submit({
                            method: 'POST'
                            ,waitMsg: 'Salvando registro ...'
                            ,waitTitle: 'Aguarde ...'
                            ,success: function(frm, act){
                                Ext.Msg.show({
                                    title: 'Registro salvo!'
                                    ,msg: act.result.message
                                    ,buttons: Ext.Msg.OK
                                    ,icon: Ext.MessageBox.INFO
                                });
                            }
                            ,failure: function(frm, act){
                                if(act.failureType === 'server'){
                                    var msg = act.result.message;
                                }else{
                                    var msg = 'Erro desconhecido!';
                                }
                                Ext.Msg.show({
                                    title: 'Erro ao salvar registro! [' + act.failureType + ']'
                                    ,msg: msg
                                    ,buttons: Ext.Msg.OK
                                    ,icon: Ext.MessageBox.ERROR
                                });
                            }
                        });
                    }
                    ,scope: this
            },{
                text: 'Desfazer'
                ,iconCls: 'x-icon-undo'
                ,handler: function(){
                    var el = Ext.ComponentMgr.get('edit-form');
                    el.getForm().reset();
                }
            },{
                text: 'Fechar'
                ,iconCls: 'x-icon-close'
                ,handler: function(){
                    this.setTitle(Ext.TITLEDEFAULT);
                    this.setIconClass(Ext.ICONCLSDEFAULT);
                    var el = Ext.ComponentMgr.get('edit-form');
                    var parent = el.getBubbleTarget();
                    parent.close();
                    this.enable();
                }
                ,scope: this
            }]
        });

        form.add({
            name: 'xaction'
            ,xtype: 'hidden'
            ,value: action
        });

        return form;
    }
});

Scripts recomendados

Palheta de cores utilizando Json e javascript não obstrutivo

Quebra de página

Calculadora Científica

Sms tipo PHP para sites java ou Html

Calculadora Javascript


  

Comentários

Nenhum comentário foi encontrado.


Contribuir com comentário




Patrocínio

Site hospedado pelo provedor RedeHost.
Linux banner

Destaques

Artigos

Dicas

Tópicos

Top 10 do mês

Scripts