You are viewing an old version of this page. View the current version.

Compare with Current View Page History

« Previous Version 4 Next »

It's common to want the user to confirm his action if it would be hard to reverse, e.g. if he asked to delete something. Here's one way to do this, using Javascript:

Link removeLink = new Link("removeLink") {
			@Override
			public void onClick() {
				// do something you want to confirm beforehand
			}
		};

removeLink.add( new SimpleAttributeModifier("onclick", "return confirm('are you sure?');"));

SimpleAttributeModifier will replace any existing onclick handler in the html. We can instead add our javascript to any existing javascript by creating our own AttributeModifier instead of using SimpleAttributeModifier:

public class JavascriptEventConfirmation extends AttributeModifier {

	public JavascriptEventConfirmation(String event, String msg) {
		super(event, true, new Model(msg));
	}

	protected String newValue(final String currentValue,
			final String replacementValue) {
		String result = "return confirm('" + replacementValue + "')";
		if (currentValue != null) {				
			result = currentValue + "; " + result;
		}
		return result;
	}
}

Then we attach the modifier to the link:

	removeLink.add(new JavascriptEventConfirmation("onclick", "are you sure?"));

If you are using the same confirmation in more than one link, you should subclass Link to encapsulate the change:

abstract public class ConfirmLink extends Link {
      public ConfirmLink(String id, String msg) {
           super(id);
           add(new JavascriptEventConfirmation("onclick", "are you sure?"));
      }

      @Override
      abstract public void onClick();
			
}

(The subclass could of course use SimpleAttributeModifier instead.)

  • No labels