Question

I am developing a web application using ExtJS to build GUI and communicate with server via RESTful web-service (the returned data is formatted as JSON objects).
Now I am having problems when processing with data which contains HTML tags, Javascript codes inside; because when I set those values to Ext forms, labels, input fields, they are affected by those syntaxes.
I used this function to load data from model object to form:

form.loadRecord(model);

I have found a solution to escape HTML and JS: using

field.setValue(Ext.util.Format.htmlDecode(data)); 

but I think that is not a good solution for whole application, because the developers must do so much things: review all input fields, labels, and put that snippet to them. And after all, that is not a beautiful way to build a fast, robust and maintainable application.
So, could you please help me solution so that it can be modified at one place, and affects to the rest. Can I override the setValue/ setLabel of AbstractComponent? Or should I encode the data before rendering them? And how to decode those data? (P/S: I uses Grails framework on the server-side) Thank you so much.

Was it helpful?

Solution 2

Everything depends on your use case, but what I do is - escape all HTML code on server side, so that there are no 'forgotten' places by mistake. That of course creates problems, when these data need to be loaded in form fields, because they are escaped. The easiest solution is to override setValue for all form fields and use Extjs htmlDecode function, which will revert these values back to normal.

Ext.override(Ext.form.field.Base, {
    setValue: function(val) {
        val = Ext.util.Format.htmlDecode(val);
        return this.callParent([val]);
    }
});

OTHER TIPS

If you're using Ext.XTemplate, you can escape html in fields like this:

var tpl = new Ext.XTemplate(
    '<p>My Field: {myField:htmlEncode}</p>'
);

This link has a excellent answer by jack.slocum : https://www.sencha.com/forum/showthread.php?13913

grid.on('validateedit', function(e){
   e.value = Ext.util.Format.stripTags(e.value);
});

Util method Ext.util.Format.stripTags() removes all the html/script tags.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top