Table of contents

From Ralf Ebert:

I just changed some of my forms to show form validation results
without messages (I was fed of writing these property files). I just
want form fields with validation errors getting a special css class
(for eye catching formatting) and a general message like "check the
marked fields". I got that working in a general way, just thought I
should tell you about this use case and how I got that working
because I think it's a quite common technique and Wicket could
support it out of the box...

I think the fact that the Validators know about messages currently is
not the greatest approach because validation doesn't depend on
messages in general. Maybe validation and reacting on validation
errors could be separated a bit more.

First step: no more required messages

Ok, at first I got rid of the need to supply a message for each
form field:

    getSettings().addStringResourceLoader(new IStringResourceLoader() {
        public String loadStringResource(Component component, String key, Locale locale, String style) {
            if (key.endsWith("Validator"))
                return "Please enter a valid value for "+component.getId()+"!";
            return null;
        }
    });

Second step: CSS style validation feedback

Second thing: A form class that adds a AttributeModifier to all
form components:

    public class HighlightForm extends Form {
        private final static AttributeModifier highlightAttributeModifier = 
            new AttributeModifier("class", true, new AbstractReadOnlyModel() {
                public Object getObject(Component component) {
                    if (component.hasErrorMessage())
                        return "error";
                    return null;
                }
            });
    
        @Override
        protected void onBeginRequest() {
            visitFormComponents(new FormComponent.IVisitor() {
                public void formComponent(FormComponent formComponent) {
                    formComponent.add(highlightAttributeModifier);
                }
            });
        }
    
        public HighlightForm(String id, IModel model) {
            super(id, model);
        }
    
        public HighlightForm(String id) {
            super(id);
        }
    }

Third step: specialized feedback markup container

Third thing, a feedback markup container that is shown only when
there was a validation error (message can be specified in the markup
this way)

    public class SimpleFeedbackPanel extends WebMarkupContainer
    {
    
        /**
         * @see wicket.Component#Component(String)
         */
        public SimpleFeedbackPanel(final String id)
        {
            super(id);
            setModel(new FeedbackMessagesModel());
        }
    
        @Override
        public boolean isVisible() {
            return !((List) getModelObject()).isEmpty();
        }
    
    }
  • No labels