how to check if a model has data rows with javascript?

  • 1
  • Question
  • Updated 2 years ago
I'm trying to run some if statements in javascript and need to check if a model has data rows. I'm sure there's some easy way to do this, but couldn't find it in the api reference or on the community. 

I'm using the getFirstRow action to set a firstRow variable and then checking if firstRow is undefined. It works, but i'm sure there's a better way. 

var templates = skuid.model.getModel('ConditionTemplates');
var templateFirstRow = templates.getFirstRow();
if (templateFirstRow !== undefined){
//do stuff
}
Photo of Jack Sanford

Jack Sanford, Champion

  • 8,322 Points 5k badge 2x thumb

Posted 2 years ago

  • 1
Photo of Jeff Rutter

Jeff Rutter

  • 1,162 Points 1k badge 2x thumb
Jack!

I'm learning more and more as I work with snippets and javascript lately so hopefully I can help. I use getRows() instead of getFirstRow(). Then I set a variable that checks that last variable of the getRows() one for length which gives me the number of rows in the model.

Example:

var rows = model.getRows();
var rowsLength = rows.length;

I think this should help you out hopefully.

I hope that helps!

Jeff Rutter
Photo of Jeff Rutter

Jeff Rutter

  • 1,162 Points 1k badge 2x thumb
T

This is what I see in my console....
Photo of Jack Sanford

Jack Sanford, Champion

  • 8,322 Points 5k badge 2x thumb
Turns out there's an even simpler way! I figured out that modelName.data.length counts the records the same way as rows.length

var templates = skuid.model.getModel('ConditionTemplates');
if (templates.data.length !== 0) {
//do stuff
}
Photo of Jeff Rutter

Jeff Rutter

  • 1,162 Points 1k badge 2x thumb
Awesome...you're right that is definitely a better option! Glad to help!

Regards,

Jeff Rutter
Photo of Matt Sones

Matt Sones, Champion

  • 31,478 Points 20k badge 2x thumb
Gentlemen, just a heads-up that while .data isn't likely to go away, .getRows() is the documented way to access the model's data rows. I always recommend using the documented method.

In your example above templates.getRows().length will return the same thing as templates.data.length
Photo of Jack Sanford

Jack Sanford, Champion

  • 8,322 Points 5k badge 2x thumb
Awesome! Thanks Matt!
Photo of Jeff Rutter

Jeff Rutter

  • 1,162 Points 1k badge 2x thumb
Matt, thanks for the reminder!