Using X++ to Find if an Object Exists in the Current Model
I recently had a scenario where I needed to verify programmatically whether or not an AOT element exists in the current model. This is a very simple task if you are manually looking at an object in the AOT, but it isn’t so easy to do in X++. The issue you run into is – if the object exists initially in the Foundation model (in the sys layer) and you add to it in the usr layer portions of the AOT element exist in the Foundation model and the particular piece you added exists in a different model.
For example, on a table created in the sys layer beside the table name is the model Foundation. If you add a method to the table, beside the name of the method you see your model’s name. If you use the TreeNode class to identify which model the table exists in, it will tell you the model the currently selected node is in. So if you are on the table’s name node, you will get the Foundation model. If you happen to be on the node of the method you added, TreeNode will return the model the method exists in. The X++ code below will find the first node in the AOT element that exists in the current model and layer.
SysModelElement element, childElement; SysModelElementData elementData, childElementData; SysModelLayer layer; SysModelManifest model; TreeNode node = TreeNode::findNode(@"\Data Dictionary\Tables\Accountant_BR"); //Find the root node for this AOT element select element join elementData where elementData.ModelElement == element.RecId join model where model.RecId == elementData.ModelId && element.Name == node.AOTname() && element.ElementType == xUtilIdElements::findTreeNode(node).recordType; //Find anything on this element //in the current layer and model select firstOnly childElement join childElementData where childElementData.ModelElement == childElement.RecId && childElement.RootModelElement == element.RootModelElement join layer where layer.RecId == childElementData.Layer && layer.Layer == enum2int(currentAOLayer()) join model where model.RecId == childElementData.ModelId && model.Model == xInfo::getCurrentModelId();