First - the wrong way:
if(myRelation.getSize() > 0) {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.
//do something
}
The right way:
if(myRelation && myRelation.getSize() > 0) {We've subtly changed the question to "IF the relation is valid and the number of related records > 0 THEN do something."
//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:
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
Hmmmm.... but if the relation isn't valid - won't that error as well? Good tip, though Robert - THANKS for posting! :)
Yes you can test it yourself:
if ( !utils.hasRecords(undefined)) {
application.output("Nothing here...")
}
or
if ( !utils.hasRecords(null)) {
application.output("Nothing here...")
}
Post a Comment