Sunday, July 19, 2009

Referencing a table field

This is a little post about the various ways you can address fields from tables.

Here are some examples.

This could be a static methode, declared on the table CustTable. The goal is to retrieve the customer name, based from the account code.


static Name GetCustName(CustAccount _custAccount)

{ CustTable custTable;
;
select firstonly custTable
index hint AccountIdx
where custTable.AccountNum == _custAccount;

return custTable.Name;
}

This is probably the most common way used.
There are some alternatives for this:

static Name GetCustName(CustAccount _custAccount)
{ CustTable custTable;
;
select firstonly custTable
index hint AccountIdx
where custTable.AccountNum == _custAccount;

return custTable.(2);
}

As you can see here, you can get access to the field by using it's fieldid. You can look up the fieldid in the AOT, as it is the first property displayed for a field of a table.

But maybe you don't have the fieldid, and would like to retrieve the value by using the field name instead. As always, Ax has a function that comes in handy. You can use fieldname2id.


static Name GetCustName(CustAccount _custAccount)
{ CustTable custTable;
;
select firstonly custTable
index hint AccountIdx
where custTable.AccountNum == _custAccount;

return custTable.(fieldname2id(tablenum(CustTable),'Name'));
}

Maybe a bit less known: You are not required to declare the CustTable table identifier. You can write code like this as well.

static Name GetCustName(CustAccount _custAccount)
{ ;
return (select firstonly custTable
index hint AccountIdx
where custTable.AccountNum == _custAccount).Name;
}


Make sure you use the brackets before and after the select statement.

So, plenty of options, whichever approach works for you.

No comments:

Post a Comment