Overrides.js 7.79 KB
/**
 * Contains Common overrides and extentions
 * 
 */

/**
 * Adds functions with predefined configs
 */
Ext.override(Ext.Msg, {
	onShow: function() {
        this.callParent(arguments);
        this.center();
        
        // This will fix trace information block
        if(!Ext.isEmpty(Ext.query('div.x-msg-trace')) && !Ext.isEmpty(Ext.query('div.x-msg-error'))) {
        	var error = Ext.get(Ext.query('div.x-msg-error')),
        	    trace = Ext.get(Ext.query('div.x-msg-trace'));
        	
        	if(trace.first().getHeight() + error.first().getHeight() > this.body.getHeight()) {
        	   trace.first().setHeight(this.body.getHeight() - error.first().getHeight());
        	}
        }
    },
    
    showInfo: function(config) {
        Ext.Msg.show(Ext.apply({
            autoScroll: true,
            title: 'Info',
            msg: '',
            icon: Ext.Msg.INFO,
            buttons: Ext.Msg.OK
        }, config || {}))
    },
            
    showError: function(cfg) {
    	if(Ext.isObject(cfg.msg)) {
            if(cfg.msg.tpl) {
                if(Ext.isArray(cfg.msg.tpl) || Ext.isString(cfg.msg.tpl)) {
                    cfg.msg = new Ext.XTemplate(Ext.isArray(cfg.msg.tpl) ? cfg.msg.tpl.join('') : cfg.msg.tpl).apply(cfg.msg.data || {});
                }
                else if(cfg.msg.tpl.isTemplate) {
                    cfg.msg = cfg.msg.tpl.apply(cfg.msg.data || {});
                }
            }
            else if(cfg.msg.error) {
                cfg.msg = new Ext.XTemplate(
                    '<div class="x-msg-error">',
                    '<tpl if="code">Error code: {code}<br/></tpl>',
                    '<tpl if="type">Error type: {type}<br/></tpl>',
                    'Message: <tpl if="message">{message}</tpl><tpl if="!values.message">Unknown error</tpl><br>',
                    '<tpl if="file">File: {file}<br/></tpl>',
                    '<tpl if="line">Line: {line}<br/></tpl>',
                    '</div>',
                    '<tpl if="traces">',
                        '<div class="x-msg-trace"><tpl for="traces">',
                            '({line}) {file}: <div class="x-msg-trace-detail">',
                                '<tpl if="type == \'-&gt;\'">{class}-&gt;{function}()</tpl>',
                                '<tpl if="args && args.length &gt; 0"><div><b>Arguments:</b> {[ Ext.encode(values.args) ]}</div></tpl>',
                            '</div>',
                        '</tpl></div>',
                    '</tpl>'
                ).apply(cfg.msg.error);
            }
        }
    	
        Ext.Msg.show(Ext.apply({
            autoScroll: true,
            title: 'Error',
            msg: '',
            icon: Ext.Msg.ERROR,
            buttons: Ext.Msg.OK
        }, cfg || {}))
    }
});


/**
 * Adds default settings to the Ext.data.Connection
 * The main goal is to change onComplete function to handle common server exceptions
 */
Ext.override(Ext.data.Connection, {
	// Default request path
    url: '.',
    
    // Default timeoute
    timeout: 380000,

    /**
     * Set guest state to the authorization controller
     */
    setGuest: Ext.emptyFn,

    /**
     * Return isGuest current value
     * @return {Boolean}
     */
    getGuest: Ext.emptyFn,
    
    /**
     * Finds meta tag in the document to set application base url
     * @return {string}
     */
    getBaseUrl: function() {
    	if(!Ext.isDefined(this.baseUrl)) {
    		this.baseUrl = (Ext.query('meta[name=application-url]')[0] || { content: '.' }).content;
    		
    		this.baseUrl.replace(/[\/\\]+$/, "");
    		this.url = this.baseUrl;
    	}
    	
    	return this.url;
    },
    
    /**
     * Returns RESTful url using base url and passed route
     * @return {string}
     */
    getRestUrl: function() {
    	var route = [];
    
        Ext.iterate(arguments, function(value) {
            this.push(value);
        }, route);
        
        route = route.join('/');
    	route.replace(/^[\/\\]+/, "");
    	return [this.getBaseUrl(), '/index.php/', route].join('');
    },
    
    /**
     * To be called when the request has come back from the server
     * This override needs to catch specific server exceptions and stop callback execution
     * @private
     * @param {Object} request
     * @return {Object} The response
     */
    onComplete : function(request) {
        var me = this,
            options = request.options,
            result,
            success,
            response;
        
        try {
            result = me.parseStatus(request.xhr.status);
        } catch (e) {
            // in some browsers we can't access the status if the readyState is not 4, so the request has failed
            result = {
                success : false,
                isException : false
            };
        }
        
        success = result.success;
        
        // Run success
        if (success) {
            response = me.createResponse(request);
            me.fireEvent('requestcomplete', me, response, options);
            Ext.callback(options.success, options.scope, [response, options]);
        } else {
            if (result.isException || request.aborted || request.timedout) {
                response = me.createException(request);
            } else {
                response = me.createResponse(request);
            }
            
            // Keep unauthorized statuses
            if(Ext.isEmpty(me.getGuest()) && (response.status != 404 || response.status != 500)) {
                me.setGuest(true);
            } 
            else {
            	if(options.proxy && options.proxy.isProxy) {
            		var data = response.responseText ? Ext.decode(response.responseText) : {};
            		
            		Ext.Msg.showError({
            			title: data.error.title || 'Error',
            			msg: {
            				error: data.error
            			},
            			buttons: Ext.Msg.OK
            		});
            	}
            	else {
                    me.fireEvent('requestexception', me, response, options);
            	}
                Ext.callback(options.failure, options.scope, [response, options]);
            }
        }
        if (!Ext.isDefined(me.isGuest)) {
            Ext.callback(options.callback, options.scope, [options, success, response]);
        }
        
        delete me.requests[request.id];
        return response;
    }
});


/**
 * Changes for the toolbar element
 */
Ext.override(Ext.Toolbar, {
    // Adds function to the toolbar to return input element's values
	getValues: function() {
		var params = {},
		    items = this.query('searchfield,textfield,numberfield,checkbox,radio,combo');
		
		    Ext.each(items, function(item){
		    	this[item.name || item.itemId || item.getId()] = item.getValue();
		    }, params);
		return params;
	}
});


/**
 * Additional component to initiate query request on enter key event
 */
Ext.define('Ext.form.SearchField', {
    extend: 'Ext.form.field.Text',
    alias: 'widget.searchfield',
    enableKeyEvents: true,
    
    // If field is in the toolbar than this option may points to button
    // or put here function
    handler: null,
    
    // Add specialkey listener
    initComponent: function() {
        this.callParent();
        if(!Ext.isEmpty(this.handler)) {
            this.on('specialkey', this.checkEnterKey, this);
        }
    },

    // Handle enter key presses, execute the search if the field has a value
    checkEnterKey: function(field, e) {
        var value = this.getValue();
        if (e.getKey() === e.ENTER) {
            if(Ext.isFunction(this.handler)) {
            	this.handler();
            }
            else if(Ext.isString(this.handler)) {
            	var point = this.up('toolbar').query('#' + this.handler);
            	if(point.length > 0 && point[0].getXType() == 'button') {
            		point[0].fireEvent('click',point[0]);
            	}
            }
        }
    }
});