Monday, June 27, 2011

Servoy TIP: Referencing A Relation In Code

OK - here's the first Servoy QuickTip - and it has to do with relations. When you're using relations in a conditional statement - and especially when you're using them in calculations - make sure you test for the existence of the relation first.


First - the wrong way:
if(myRelation.getSize() > 0) {
  //do something
}
If you leave the code like this - and the relation is invalid for the current record - Servoy will complain. The above code is saying "IF the number of related records > 0, THEN do something." However, if the relationship is invalid - then Servoy will throw an "invalid" error. You should always check and make sure the relation is valid before you try to access any of the functions on a relation.

The right way:
if(myRelation && myRelation.getSize() > 0) {
  //do something
}
We've subtly changed the question to "IF the relation is valid and the number of related records > 0 THEN do something."

Another way to say the same thing would be to ask the question: "What color is your sister's hair?" when someone only has brothers. Their answer is going to be "I have no sister." (error!). So, you should ask the question: "If you have a sister, what color is her hair?"

3 comments:

Robert Ivens said...

Hi Bob,

I think the most bulletproof way (and it will simplify your example in this case) is to use the utils.hasRecords() function.
So your code would be:
if( utils.hasRecords(myRelation) ) {
//do something
}

This way you tackle 2 things at once.
1) you check if the relation (foundset really) is valid
2) you check if there are any records

Bob Cusick said...

Hmmmm.... but if the relation isn't valid - won't that error as well? Good tip, though Robert - THANKS for posting! :)

Robert Ivens said...

Yes you can test it yourself:

if ( !utils.hasRecords(undefined)) {
application.output("Nothing here...")
}

or

if ( !utils.hasRecords(null)) {
application.output("Nothing here...")
}

Web Analytics