Tuesday, July 24, 2012

validation at datatable level, datatable row iteration

Suppose we have a list of object which is rendered as a h:dataTable. User can modify and delete the list item. But we must make sure there is at least one item in the list. The list can not be empty.

We could attach the validation rule as a PostValidationEvent Listener in datatable. But how can we know the value in the list. be aware of that we are at PostValidation stage. The value has not be pushed to model layer. We can not check the model layer. We have check all the local value in the input fields.  So it boils down to how to access the row values programmatically.

Here is how I do it.
int size=0;
HtmlDataTable table=(HtmlDataTable)component
                HtmlColumn column=(HtmlColumn)table.getChildren().get(0);
                UIInput input=null;
                for(UIComponent rowfield: column.getChildren())
                {
                    if (rowfield instanceof UIInput)
                    {
                        input=(UIInput)rowfield;
                        break;
                    }
                }
                if (input!=null)
                {
                    for (int i=0; i<table.getRowCount(); i++)
                    {
                        table.setRowIndex(i);
                        if (input.getLocalValue()!=null)
                        {
                            logger.info(input.getLocalValue().toString());
                            size++;
                        }
                    }
                }
The trick here is table.setRowIndex(i). Once it is called, your input field in datatable has correct state.


No comments:

Post a Comment