Sunday, November 23, 2008

Confirmation Dialog - Wicket

Sometimes we want the confirmation from the user before doing the request. Say for example, we have a delete button on our application. The user accidently clicks on the delete button due to which he might lose the important record. In case he got a dialog saying, "Hey dude, wanna delete this?" with Yes/No button, he can safely avoid the disastrous deletion. So how to do we do that in wicket ?


import org.apache.wicket.Component;
import org.apache.wicket.behavior.AbstractBehavior;
import org.apache.wicket.markup.ComponentTag;
import org.apache.wicket.markup.html.form.Button;
import org.apache.wicket.markup.html.link.Link;

/**
* Javascript Confirmation box.
* Can be used for confirmation before deletion of a record.
*
* @author Srikanth NT
*/
public class ConfirmationBoxRenderer extends AbstractBehavior {

/** Serial Version UID. */
private static final long serialVersionUID = -3398632388257916688L;

/** Message to be desplayed in the confirm box. */
private String message;

/**
* Constructor.
* @param message Message to be shown in the confirm box.
*/
public ConfirmationBoxRenderer(final String message) {
super();
this.message = message;
}

/**
* @param component Component to attach.
* @param tag Tag to modify.
* @see org.apache.wicket.behavior.AbstractBehavior#onComponentTag(org.apache.wicket.Component, org.apache.wicket.markup.ComponentTag)
*/
@Override
public void onComponentTag(final Component component, final ComponentTag tag) {
if (component instanceof Button || component instanceof Link) {
tag.getAttributes().remove("onclick");
tag.getAttributes().put("onclick", "return confirm('" + message + "')");
}
}
}


I have created a simple behavior which you can attach to the normal Button or Link.