Update financial dimension value from X++ code in Dynamics 365

The information in this post is based on Dynamics 365. It should also work in Dynamics AX 2012, but I haven’t explicitly tested it.

I was recently tasked with updating the value of a single financial dimension based on some form logic.

As you probably know, since Dynamics AX 2012 financial dimensions are stored in separate tables and referenced through a RecId, usually in a DefaultDimension field.

The whole framework for handling dimensions is somewhat complex and I often find myself having to re-read documentation on it, perhaps because it’s not something I work with all that often.

Anyway, updating a field in an existing dimension set is something that comes up frequently, so I thought I’d do a write up of my favorite recipe 😉

A static utility method could look like this:

public static DimensionDefault updateDimension(
                             DimensionDefault _defaultDimension,
                             Name             _dimensionName,
                             DimensionValue   _dimensionValue)
{
    DimensionAttribute                  dimAttribute;
    DimensionAttributeValue             dimAttributeValue;
    DimensionAttributeValueSetStorage   dimStorage;
    DimensionDefault                    ret;
    ;

    ret = _defaultDimension;

    ttsBegin;

    dimStorage      = DimensionAttributeValueSetStorage::find(_defaultDimension);
    dimAttribute    = DimensionAttribute::findByName(_dimensionName);

    if (_dimensionValue)
    {
        dimAttributeValue = DimensionAttributeValue::findByDimensionAttributeAndValue(dimAttribute, _dimensionValue, true, true);
        dimStorage.addItem(dimAttributeValue);
    }
    else
    {
        dimStorage.removeDimensionAttribute(dimAttribute.RecId);
    } 

    ret = dimStorage.save();

    ttsCommit;

    return ret;
}

The method returns a new (or the same) DimensionDefault RecId, so if updating a dimension value for a record – which is probably the most common scenario – you should make sure to update the dimension field on that record with the new value.