Saturday, September 13, 2014

How to add a new relation on a table from code

If you got into troubles, like me, trying to add a new relation on a table from X++, this code will save your day. The main point here is the code 251. Read my lips: two-five-one. Because reflections work on everything when you know the code.



private void createTableRelationInAOT(TreeNode _treeNodeTableRelation, TableName _relatedTableName, FieldName _relatedFieldName)
{
#Properties    
    TreeNode            treeNodeRelations;
    TreeNode            tableRelation;
    ReferenceNode       tableRelationFields;

    if(treeNodeTableRelation && _relatedTableName && _relatedFieldName)
    {
        treeNodeRelations = _treeNodeTableRelation.AOTfindChild(#PropertyRelations);
        tableRelation = treeNodeRelations.AOTadd(relatedTableName);
        tableRelation.AOTsetProperty('Table', relatedTableName);
        //can anyone tell me how I could guess this secret code??
        tableRelationFields = tableRelation.AOTaddSubNode(251); 
        //never change the order of two these properties! it works only like follows
        tableRelationFields.AOTsetProperty(#PropertySecField, relatedFieldName);
        tableRelationFields.AOTsetProperty(#PropertyRelatedField, relatedFieldName);
    }
    _treeNodeTableRelation.AOTsave();

}


Happy deciphering!

Sasha Nazarov added:

 "251" corresponds to #NT_DBNORMALREFERENCEFIELD

in TreeNodeSysNodeType macro:
#define.NT_DBREFERENCE( 250)
#define.NT_DBNORMALREFERENCEFIELD( 251)
#define.NT_DBTHISFIXEDREFERENCEFIELD( 252) #define.NT_DBEXTERNFIXEDREFERENCEFIELD( 253)

2 comments:

Sasha Nazarov said...

Hi

"251" corresponds to #NT_DBNORMALREFERENCEFIELD in TreeNodeSysNodeType macro:

#define.NT_DBREFERENCE( 250)
#define.NT_DBNORMALREFERENCEFIELD( 251)
#define.NT_DBTHISFIXEDREFERENCEFIELD( 252)
#define.NT_DBEXTERNFIXEDREFERENCEFIELD( 253)

wojzeh said...

Саша, спасибо большое! Добавлю в статью!