Using VarMap/GlobalVarMap usage example with Intgegration toolkit?

Using Integration Toolkit. Need some help leveraging VarMap and globalVarMap to go from database → class → data on the HMI.

Here’s a example of the object I would like to do it with/load from the database -

create table products (
    name varchar(20) primary key,
    abbreviation varchar(5),
    element varchar(4)
);

insert into products
VALUES ('Nitrogen', 'NIT', 'N2');
insert into dbo.products
VALUES ('Oxygen', 'OXY', 'O2');

and the class defined as

class Product(system.util.VarMap):#Instead of smartmap
	def __init__(self, name, abbreviation, element):
		self.name = name
		self.abbreviation = abbreviation
		self.element = element

Then I populate I think like so -

def populateProducts():
	products = system.db.runQuery("SELECT * FROM dbo.Products")
	for (name, abbr, element) in products:
		bvm = system.util.globalVarMap("abbr")
		bvm = schemas.product.Product(name, abbr, element)
		bvm.refresh()
system.util.invokeAsynchronous(populateProducts)

Then on my screen I am trying to say access the “element” property of the globalVarMap({Root Container.abbr})['element'] where {Root Container.abbr} is ‘NIT’ but I am not seeing anything come through. I am obviously doing something wrong. Can someone please guide me?

Ok I messed up a bit with my populate code. This works better -

def populateProducts():
    bvm = system.util.globalVarMap("Products")
    ds = system.db.runQuery("SELECT name, abbreviation, element FROM Products")
    for row in ds:
        abbr = row['abbreviation']   # e.g. "NIT" or "OXY"
        prod = schemas.product.Product(row['name'], abbr, row['element'])
        bvm[abbr] = prod             # store product under its abbreviation
    bvm.refresh()                    # notify all bindings using this map
system.util.invokeAsynchronously(populateProducts)

Keep all my products under the Products key and then this expression worked

globalVarMap("Products")[{Root Container.abbr}]['element']

Yes, the key given to globalVarMap() should be a constant in almost all cases.

Consider reworking your espression as follows:

coalesce(globalVarMap("Products")[{Root Container.abbr}], asMap())['element']

That will allow the final lookup to return a null instead of an error if the abbreviation doesn't exist in the globalVarMap (yet).

1 Like