Thursday, January 3, 2013

Global findByRecId() function

AX 2012 relies heavily on foreign key relations for its table relations. A consequence of this change is that now developers will be accessing tables using recIds rather than using any other primary key, which was the norm before. So far so good. So what's the problem, you may ask.
Now this will also mean that developers will need to write lot more findByRecId() methods on tables. That is redundancy. We can refactor this method as a generic template and write it in Global class.

One example I found in an excellent blog post.
http://www.doens.be/2009/07/select-a-record-from-a-table-when-you-only-have-the-tableid/

public Common findByRecId(TableId _tableId, RecId _recId, Boolean _forUpdate = false)
{
    Common      common;
    DictTable   dictTable;
    ;
    dictTable = new DictTable(_tableId);
    common = dictTable.makeRecord();
 
    common.selectForUpdate(_forUpdate);
 
    select common
    where common.RecId == _recId;
 
    return common;
}
Now when you need to access a record buffer in a table MyTable using record id, instead of writing it as MyTable::findByRecId(_recId), you can use findByRecId(tableNum(MyTable), _recId)

No comments:

Post a Comment