Monday, March 15, 2010

Check all mixin

This is a VERY simple mixin that turns a regular checkbox into a controller checkbox. It's a nice example of how easy it is to create these elegant little mixins and components in Tapestry 5!

Example: <input type="checkkbox" t:type="any" t:mixins="checkall" t:controlledClass="element-selected"/>

CheckAll.java

/**
* Mixin for checkboxes that should control the checked state of a group of other checkboxes. All the controlled checkboxes need to
* have the CSS class specified in the controlledClass parameter.
*
* @author Inge
*
*/
public class CheckAll {

/**
* The controller checkbox that this mixin applies to.
*/
@InjectContainer
private ClientElement container;

@Environmental
private RenderSupport renderSupport;

/**
* The CSS class that all controlled checkboxes must have to be controlled by the master checkbox.
*/
@Parameter(required = true, defaultPrefix = BindingConstants.LITERAL)
private String controlledClass;

void afterRender() {
renderSupport.addScript("new CheckAll('%s', '%s')", container.getClientId(), controlledClass);
}
}


CheckAll.js

var CheckAll = Class.create( {
initialize : function(controllerId, controlledClass) {
this.controller = $(controllerId);
this.controlledClass = controlledClass;
this.controller.observe('change', this.toggle.bindAsEventListener(this));
},
toggle: function() {
var checked = this.controller.checked;
var controlledCheckboxes = $$('input.' + this.controlledClass);
controlledCheckboxes.each(function(checkbox) {
checkbox.checked = checked;
});
}
});

1 comment:

  1. Great post! thanks

    With this I check all the checkboxes of the page that I'm in a grid. But, could I check all the checkboxes of the grid? (if it has more than 1 page)

    Thanks a lot
    Alberto

    ReplyDelete