Problem

How do I set the value of a column-table using the table events.


Solution

In some cases the value to be calculated is too complex and we cannot insert the elaboration into the property "Expression" of the column. To solve this problem we use the potential that events of the table provide us.
Suppose we have the table test.Product with the following columns:

Code
CheckDigit
Description
Price

Suppose also that the column CheckDigit must contain a character resulting by a complex calculation based on the value of the column Code.
To do this we set the column CheckDigit to type "Char" (the columns that contain calculated value through the events need to be saved in the database and therefore can not be of type "Calculated").
Here is the code using the event beforeSetValue to validate input and afterSetValue for the calculation:

beforeSetValue(dataweb.datastore.event.TableSetValueEvent e){
   if (e.getTable()==thisTable){
      if (e.getColumnName().equals("Code")){
         if ((e.getValue()==null) || (e.getValue().length()!=6)){
            throw new dataweb.datastore.DataStoreException("Code must be 6 characters length.");
         }
      }
   }
}

afterSetValue(dataweb.datastore.event.TableSetValueEvent e){
   if (e.getTable()==thisTable){
      if (e.getColumnName().equals("Code")){
         String chk = getCheckDigit(e.getValue());
         thisTable.setValue("CheckDigit", chk);
      }
   }
}

getCheckDigit(String s){
   // SIMPLE IMPLEMENTATION FOR EXAMPLE PROUPOSE
   String sret=null;
   if (s!=null){
      if (s.startsWith("A")){
         sret="X";
      }else{
         sret="Y";
      }
   }
   return sret;
}

Published in Wed, 05 January 2011 12:38