How can I change the way GRAILS GSP fieldValue formats Integers?

前端 未结 8 1659
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-16 06:09

I have a field in my domain object which I define as an Integer...

Integer minPrice

I then access it in a GSP page as follows:



        
8条回答
  •  执笔经年
    2020-12-16 06:50

    I found the best way to handle this was doing what Victor Sergienko (upped btw) hinted at with using a PropertyEditor.

    Create an editor for Integer, put in src/groovy:

    class IntegerEditor extends PropertyEditorSupport {
        void setAsText(String s) {
            if (s) value = s as Integer
        }
    
        public String getAsText() {
            value
        }
    }
    

    and register it using a PropertyEditorRegistrar (also in src/groovy):

    class MyEditorRegistrar implements PropertyEditorRegistrar {
        public void registerCustomEditors(PropertyEditorRegistry reg) {
            reg.registerCustomEditor(Integer, new IntegerEditor())
        }
    }
    

    add your registrar into the spring config (grails-app/conf/spring/resource.groovy):

    beans = {
        customEditorRegistrar(MyEditorRegistrar)
    }
    

    From now on any Integers that are bound, receive errors (or not) and then redisplayed with the fieldValue tag should be displayed by Integer's default toString - you can customise this behaviour in the editor by amending the getAsText implementation.

    Personally I would create a wrapper for this kind of thing so you can set up an editor just for that type rather than across the board for a frequently used type. Though I realise this would mean a little bit of mapping when persisting to the DB...

提交回复
热议问题