Thursday, February 20, 2020

How to replace a financial dimension value in D365

Thanks to Denis Trunin's article, we can easily implement something like this in D365FO.


public static DimensionDefault setValueToDefaultDimension(DimensionDefault _dimensionDefault, RefRecId _dimensionAttributeRecId, DimensionValue  _newDimensionValue)
    {
        DimensionAttributeValueSetStorage   dimStorage;
        DimensionDefault                    newDimensionDefault = _dimensionDefault;
        DimensionAttributeValue             dimensionAttributeValue;
        if (_dimensionAttributeRecId)
        {
            dimStorage = DimensionAttributeValueSetStorage::find(_dimensionDefault);
            if (_newDimensionValue)
            {
                dimensionAttributeValue = DimensionAttributeValue::findByDimensionAttributeAndValue(DimensionAttribute::find(_dimensionAttributeRecId), _newDimensionValue, false, true);
                dimStorage.addItem(dimensionAttributeValue);
            }
            else
            {
                dimStorage.removeDimensionAttribute(_dimensionAttributeRecId);
            }
            newDimensionDefault = dimStorage.save();
        }
        return newDimensionDefault;
    }


Then, say, we need to replace Department from Operations to Client Services for Ahmed Barnett in USMF.


static void setNewFinDimValueForEmployee(HcmWorkerRecId _worker, CompanyInfoRecId _legalEntity, Name _dimensionName, DimensionValue _dimensionValue)
    {
        HcmEmployment hcmEmployment = HcmEmployment::findByWorkerLegalEntity(_worker, _legalEntity);
        ttsbegin;
        hcmEmployment.selectForUpdate(true);
        hcmEmployment.validTimeStateUpdateMode(ValidTimeStateUpdate::Correction);
        DimensionDefault newDim = DimensionHelper::setValueToDefaultDimension(hcmEmployment.DefaultDimension, DimensionAttribute::findByName(_dimensionName).RecId, _dimensionValue);
        hcmEmployment.DefaultDimension = newDim;
        if(hcmEmployment.validateWrite())
        {
            hcmEmployment.update();
        }
        ttscommit;
    }
Here you go.




public static void main(Args _args)
    {
        HcmWorkerRecId              _worker         = 22565420995; //Ahmed Barnett
        CompanyInfoRecId            _legalEntity    = 22565422580; //USMF
        Name                        _dimensionName  = 'Department';
        DimensionValue              _dimensionValue = '028'; //Currently 026
        DimensionHelper::setNewFinDimValueForEmployee(_worker, _legalEntity, _dimensionName, _dimensionValue);
        Info(strFmt("Employee fin dim value changed!"));
    }


No comments: