November Newsletter Tip - Using Associative Arrays in Servoy

Find out how to get things done with Servoy. Post how YOU get things done with Servoy

November Newsletter Tip - Using Associative Arrays in Servoy

Postby cbenassi » Fri Oct 24, 2008 6:16 pm

This month, Servoy would like to thank Jason Pierson from Agilus Llc for sharing with us his tip - Using Associative Arrays in Servoy.

Traditional Arrays
Arrays are a powerful tool that every Javascript programmer can benefit from. Arrays can be thought of like a filing cabinet drawer. Picture every manila folder in the drawer having a number on the tab for identification and each folder can hold a value.

For instance:

var myArray = new Array()
myArray[0] = 100
myArray[1] = ‘some text’

In this example, the filing cabinet drawer is called myArray. The first folder in the drawer is identified and accessed using myArray[0], the second folder would be myArray[1], etc. Arrays are indexed starting at 0 (zero). This traditional use of an array is very common and the elements of the array can easily be accessed using FOR loops and variables to iterate through the positions of the array.

For example:

for(var x = 0; x < myArray.length; x++)
{
application.output(myArray[x])
}

That’s all I’m going to say about traditional use of arrays. Now we’ll move on to Associative Arrays and explore some simple examples to get your creative juices going.

Associative Arrays

Go back to our file cabinet drawer analogy for a minute. Rather than using a number on the tab of the folder to identify each location, which would make it very hard to find a desired folder if you used this in real life, we’re going to put words on the tab, making it very easy to find a file folder.

Here’s how it works:

var myArray = new Array()
myArray [‘car’] = ‘Ford Mustang GT’
myArray [‘truck’] = ‘Nissan Titan’

We have now created what is called a key/value pair in an associative array.

Key Value
------ ----------------------
Car Ford Mustang GT
Truck Nissan Titan

If we ever want to see what the value of ‘car’ is in our array, we can access it using myArray[‘car’] and it will return the value of ‘Ford Mustang GT’.

Let me give some real-world examples of how I use associative arrays in my every day programming. Recently I wrote an application that deals with incoming orders for products. As I import each text file with the list of orders and the associated items, I have to check inventory in an external database and make sure there is available product on-hand. I do not have permissions to modify the external database to update the quantities, so I have to track that myself using an associative array.

Here’s how I use an associative array to track inventory levels by product_id:

#######################################

// Load the array aItems using the product_id as the key and qty_on_hand as the value
var aItems = new Array()
var fs_inventory = databaseManager.getFoundSet(controller.getServerName(), ‘inventory_table’)

// Get all the records in inventory loaded into my foundset
fs_inventory.find()
fs_inventory.search()

// Loop thru all the items and add them to the array
var itemCount = fs_inventory.getSize()
for(var x = 1; x <= itemCount; x++)
{
fs_inventory.setSelectedIndex(x)

// Here is where we load our associative array
aItems[fs_inventory.product_id] = fs_inventory.qty_on_hand
}

// Now that our array is loaded, we can start processing orders and check our inventory levels
…some code here to read the text file and create a dataset
…some code here to get an item and qty ordered from the dataset
…store the product_id in the var vItem
…store the quantity ordered in var vQty

// Here’s where we use the associative array to check inventory
If(vQty <= aItems[vItem])
{
// the qty ordered is less than or equal to the qty_on_hand, so it’s okay to process this order
…some code here to create the order with the item
// we need to decrement inventory for this item so we track how many we’ve used up
aItems[vItem] -= vQty // notice the minus sign just before the equals sign
}
else
{
…some code here to backorder the item because there’s not enough inventory
}

#######################################

The secret sauce in this code is where we check the ordered quantity (vQty) against the inventory on-hand for the particular product_id ( aItems[vItem] ). If you were to run this line of code:

application.output(aItems[vItem])

You would see a number in your output console, which represents the qty_on_hand from the inventory database. We’re passing our array a key (vItem) and it gives us back the corresponding value it is storing for us (qty_on_hand).

Just to wrap up the file drawer analogy, we initialized the aItems array by putting a label on the file folder for each product_id in the database. Then we stored the qty_on_hand value in the folder. If we ever want to know how much inventory we have left, we just give our array a key and it returns the value. This is analogous to opening a file drawer, looking for the desired name on a folder tab, and then opening the folder to see its contents.


Using Associative Arrays when working with forms in Servoy

As a final tip, many objects within Servoy are stored as associative arrays. You can use this information to write reusable, abstracted code that can be put into a library of reusable methods. Here’s an example:

You could create a new record on a form with the following code:

forms.myForm.controller.newRecord()

However, this becomes hard coded and cannot be reused in a generic global method. So, this is not the best approach. A better way is to use the associative arrays built into Servoy.

Create a global method called newRec() with the following code:

var frm = application.getMethodTriggerFormName()
forms[frm].controller.newRecord()

Attach this method to a button called NEW on your form. When you run your form and click on the NEW button, this method will automatically determine the form name of the form that called it, then use that form name to dynamically call the newRecord() method at runtime. Servoy uses associative arrays to store forms, allowing us to use a variable (frm) to represent the form name.

This:
forms.myForm.controller.newRecord()

is equivalent to:
var frm = ‘myForm’
forms[frm].controller.newRecord()

Many objects can be dynamically accessed at runtime using this concept of associative arrays in Servoy. If you master these concepts, you will begin to write powerful, efficient, and reusable code. There is a lot of information on the web regarding Javascript and associative arrays. You will also find associative arrays referred to as a Hash. I’ll leave it to you to read up on these topics further.

Enjoy!
Jason Pierson
Agilus LLC
http://www.servoyan.com
cbenassi
 
Posts: 416
Joined: Tue Mar 20, 2007 7:53 pm
Location: Thousand Oaks, California

Return to How To

Who is online

Users browsing this forum: No registered users and 3 guests