Form value change listener

Hi all,
I have an issue submitting the form. I have a page with a form on it and I want to add a value change listener for it so that when user leaves the page, if there is any change, it will notify if user wants to save the form or not.
I try form.addListener(new ValueChangeListener(){…}) and it doesnot work (of course).
Any idea?

How about calling form.isModified() when the user is leaving the page? That method will return true/false depending if the data has changed.

Sorry for digging out this old post, but how - if ValueChangeListener does not work - can I enable the “Save” button when the content of the form has changed?

Thanks,
Roland

Using the isModified() works somewhat as follows:

        form.setWriteThrough(false); // Enable buffering
...
        final Button submit = new Button("Save");
...
        // Make modification to enable/disable the Save button
        form.setFormFieldFactory(new DefaultFieldFactory() {
            @Override
            public Field createField(Item item, Object propertyId, Component uiContext) {
                final AbstractField field = (AbstractField)
                        super.createField(item, propertyId, uiContext);
                field.addListener(new ValueChangeListener() {
                    @Override
                    public void valueChange(ValueChangeEvent event) {
                        submit.setEnabled(form.isModified());
                    }
                });
                field.setImmediate(true);
                
                return field;
            }
        });

However, this is really awkward with TextFields, as the value change event is sent when the focus moves out of the field, not when the user types in the field. You can use a TextChangeListener to detect modification as the user types. You may want to disable the listener after the modification is detected, unless you want to detect a possible unmodification as well. Detecting unmodification would require some extra logic as the form fields do not detect it.

If you’re a Pro Account subscriber, see article
#279
for some more details.