web
You’re offline. This is a read only version of the page.
close
Skip to main content

Announcements

No record found.

News and Announcements icon
Community site session details

Community site session details

Session Id :
Microsoft Dynamics CRM (Archived)

Transform retrieved field value to another value

(0) ShareShare
ReportReport
Posted on by 1,257

Hi Knowledgeable people :)

I'm trying to do the following... I'm retrieving a picklist field from accounts to a script to send data to another system via web services, but I have to map the retrieved value to another value, for example, if the picklist retrieved value is 1 I have to send the value 35...

So until the retrieving, all is good, but I'm not sure how to do the map or the transformation of the value, and I will appreciate so much your guidance or clues on to achieve this goal... I've been tried doing a switch case to "map" the retrieved value to the "send" value, but when I'm trying to send the switched value outside the switch case, it gets null or undefined.

Here is the code

  /***************************************************************************/

function SendDataFromWS() {
	
		
	var getguid =Xrm.Page.data.entity.getId();
		
	var getAccountId = Xrm.Page.getAttribute("parentaccountid").getValue();
	
	if (getAccountId != null) {
     var nameAcc = getAccountId[0].name; 
     var idAcc = getAccountId[0].id; 
     var entityTypeAcc = getAccountId[0].entityType;
	 var idAccString = idAcc.slice(1, -1);
	}
	
	/*************** Get Account Data Start ***************/
	
	if (getAccountId){
		
		var AccountInfo = my.oData.GetEntityRecords("Account", null, "IsCustomerAccount,IndustryLookupField,CompanySizAccountField,AccountId", "AccountId eq (guid'" + getAccountId[0].id + "')", false, null, null, null);
	
		if (getAccountId != null && getAccountId[0] != null) {

			   var accountId = getAccountId[0].id.replace("{", "").replace("}", "");
			   var req = new XMLHttpRequest();
			   var CompanySizePicklistValue_Retrieved;
			   var CustomerSize_FinalValue;

			   req.open("GET", Xrm.Page.context.getClientUrl() + "/api/data/v8.2/accounts(" + accountId + ")?$select=CompanySizAccountField", true);
			   req.setRequestHeader("OData-MaxVersion", "4.0");
			   req.setRequestHeader("OData-Version", "4.0");
			   req.setRequestHeader("Accept", "application/json");
			   req.setRequestHeader("Content-Type", "application/json; charset=utf-8");
			   req.setRequestHeader("Prefer", "odata.include-annotations=\"*\"");
			   req.onreadystatechange = function () {

				   if (this.readyState === 4) {
					   req.onreadystatechange = null;

					   if (this.status === 200) {
						   var result = JSON.parse(this.response);
						   CompanySizePicklistValue_Retrieved = result[PickListField];
						   
						   /*** Here i need to transform the retrieved value from the picklistfield to the CustomerSize Final Value to set that
								into the JSON data section  ***/
						   
						   switch(CompanySizePicklistValue_Retrieved){
								
								case 1:
								   CustomerSize_FinalValue = 1;
								   break;
								case 2:
								   CustomerSize_FinalValue = 51;
								   break;
								case 3:
									CustomerSize_FinalValue = 52;
									break;
								case 4:
									CustomerSize_FinalValue = 53;
									break;
								case 5:
									CustomerSize_FinalValue = 54;
									break;
								case 6:
									CustomerSize_FinalValue = 55;
									break;
								default:
									alert("No Company Size data on account, please help us updating the information. Thanks!");
									break;
						   }
						   
						   return CustomerSize_FinalValue;
						   							
					   } else {

						   Xrm.Utility.alertDialog(this.statusText);

					   }
				   }
			   };

			   req.send();

		if (AccountInfo && AccountInfo[0].IndustryLookupField.Id != null){
									
				var Industry = new Array();
				Industry[0] = new Object();
				Industry[0].id = "{" + AccountInfo[0].IndustryLookupField.Id + "}";
				Industry[0].name = AccountInfo[0].IndustryLookupField.Name;
				Industry[0].entityType = AccountInfo[0].IndustryLookupField.LogicalName;
									
			}else{
								
				alert("The customer doesn't contain an industry, please fill the field on the account record.");
								
			}	
		}
	}
	
	/*************** Get Account data end ***************/
	
	var getSP = Xrm.Page.getAttribute(AccountProvider).getValue();
	
	if (getSP != null) {
		var nameSP = getSP[0].name; 
		 var idSP = getSP[0].id; 
		 var entityTypeSP = getSP[0].entityType; 
	}	
		
	var getOwner = Xrm.Page.getAttribute("ownerid").getValue();
			
	if (getOwner != null) {
		 var nameOw = getOwner[0].name; 
		 var idOw = getOwner[0].id; 
		 var entityTypeOw = getOwner[0].entityType; 
	}	
		
	var getCountry = Xrm.Page.getAttribute(CountryLookupField).getValue();
			
	if (getCountry != null) {
		 var nameCo = getCountry[0].name; 
		 var idCo = getCountry[0].id; 
		 var entityTypeCo = getCountry[0].entityType; 
	}	
		
			$.ajax({
				type: "POST",
				contentType: "application/json; charset=utf-8",
				datatype: "json",
				url: URL_P,
				data: {
							
					"crmGUID": idAccString,
					"name": nameAcc,
					"countrycode": "10",
					"company_size": CustomerSize_FinalValue, /*** Here should be transformed value from the Switch Case Clausule ***/
					"Industry": "50",
					"IsCustomer": AccountInfo[0].IsCustomerAccount
				}
			}).done(function (data) {
                    var response = JSON.parse(data);
                    alert("Process Successful", response.proccesId);
        });
	}	


That's all for now and thanks in advance for any clue/friendly had for me in this case!

*This post is locked for comments

I have the same question (0)
  • Suggested answer
    RaviKashyap Profile Picture
    55,410 Moderator on at

    Hi,

    try declaring "var CustomerSize_FinalValue;" at the top so that it is is still available after the if block.

    Hope this helps.

  • Rajesh Chungath Profile Picture
    467 on at

    Please make sure CompanySizePicklistValue_Retrieved is having the value . Add debugger and check. Other Point is declare the variable "CustomerSize_FinalValue " outside of the switch otherwise it don't have scope and always returns undefined

  • Suggested answer
    Seren S Profile Picture
    402 on at

    Hi Vile Andreas,

    I think for a clean code and better performance to achieve for your scenario requires to define a basic mapTable instead of "switch case".

    This can be your mapTable variable. It is also easy to manage.

            var mapTable = [
                [1, 1],
                [2, 51],
                [3, 52]
            ];

    This functions returns the related index value to you.

            function GetMappedValue(CompanySizePicklistValue_Retrieved) {
                return mapTable[CompanySizePicklistValue_Retrieved - 1][1];
            }

    You can basically call your function to retrieved mapped value.

            var CustomerSize_FinalValue = GetMappedValue(2);

    Hope that this will give you a short clue.

    Cheers, Seren.


  • Vile Andreas Rantala Profile Picture
    1,257 on at

    Hi Seren, thanks for your answer, quick question this mapTable should be my retrieved value variable, right? I mean I have this script to get the value which is stored on this variable global "CompanySizePicklistValue_Retrieved"

    /*************** Get Account Data Start ***************/

    if (getAccountId){

    var AccountInfo = my.oData.GetEntityRecords("Account", null, "IsCustomerAccount,IndustryLookupField,CompanySizAccountField,AccountId", "AccountId eq (guid'" + getAccountId[0].id + "')", false, null, null, null);

    if (getAccountId != null && getAccountId[0] != null) {

      var accountId = getAccountId[0].id.replace("{", "").replace("}", "");

      var req = new XMLHttpRequest();

      var CompanySizePicklistValue_Retrieved;

      var CustomerSize_FinalValue;

      req.open("GET", Xrm.Page.context.getClientUrl() + "/api/data/v8.2/accounts(" + accountId + ")?$select=CompanySizAccountField", true);

      req.setRequestHeader("OData-MaxVersion", "4.0");

      req.setRequestHeader("OData-Version", "4.0");

      req.setRequestHeader("Accept", "application/json");

      req.setRequestHeader("Content-Type", "application/json; charset=utf-8");

      req.setRequestHeader("Prefer", "odata.include-annotations=\"*\"");

      req.onreadystatechange = function () {

      if (this.readyState === 4) {

      req.onreadystatechange = null;

      if (this.status === 200) {

      var result = JSON.parse(this.response);

      CompanySizePicklistValue_Retrieved = result[PickListField];

      /*** Here i need to transform the retrieved value from the picklistfield to the CustomerSize Final Value to set that

    into the JSON data section  ***/

      switch(CompanySizePicklistValue_Retrieved){

    case 1:

      CustomerSize_FinalValue = 1;

      break;

    case 2:

      CustomerSize_FinalValue = 51;

      break;

    case 3:

    CustomerSize_FinalValue = 52;

    break;

    case 4:

    CustomerSize_FinalValue = 53;

    break;

    case 5:

    CustomerSize_FinalValue = 54;

    break;

    case 6:

    CustomerSize_FinalValue = 55;

    break;

    default:

    alert("No Company Size data on account, please help us updating the information. Thanks!");

    break;

      }

      return CustomerSize_FinalValue;

      } else {

      Xrm.Utility.alertDialog(this.statusText);

      }

      }

      };

      req.send();

    if (AccountInfo && AccountInfo[0].IndustryLookupField.Id != null){

    var Industry = new Array();

    Industry[0] = new Object();

    Industry[0].id = "{" + AccountInfo[0].IndustryLookupField.Id + "}";

    Industry[0].name = AccountInfo[0].IndustryLookupField.Name;

    Industry[0].entityType = AccountInfo[0].IndustryLookupField.LogicalName;

    }else{

    alert("The customer doesn't contain an industry, please fill the field on the account record.");

    }

    }

    }

    /*************** Get Account data end ***************/

    So, in order to do a map with this field, I have to do something like this:

    CompanySizePicklistValue_Retrieved = [1, 1],

    [2, 52] etc...

    and then the function to retrieve this to the final value and put it into my Json, right?

  • Seren S Profile Picture
    402 on at

    Hi Vile Andreas,

    Based on your code, your mapTable should be;

    var mapTable = [
        [1, 1],
        [2, 51],
        [3, 52],
        [4, 53],
        [5, 54],
        [6, 55]
    ];

    The first index is your retrieved optionsetvalue. If you call the function with your retrieved value, the function should return the mapped value.

    if (this.readyState === 4) {
        req.onreadystatechange = null;
    
        if (this.status === 200) {
            var result = JSON.parse(this.response);
            CompanySizePicklistValue_Retrieved = result[PickListField];
    
            return GetMappedValue(CompanySizePicklistValue_Retrieved);
    
        } else {
    
            Xrm.Utility.alertDialog(this.statusText);
    
        }
    }


    Cheers, Seren.

  • RaviKashyap Profile Picture
    55,410 Moderator on at

    Hi Vile Andreas,

    How did you go with this? If the suggestion helped you then please close the thread by marking it as verified so that it can help others as well.

  • Vile Andreas Rantala Profile Picture
    1,257 on at

    Hi Seren,

    i'm not able to use this method you gave me, i think is the correct way to achieve my goal of do that transformation of values, but i'm receiving the following error when i trigger the button to send the data

    Cannot read property  of undefined   at GetMappedValue anonymous    at RunProcessOnOpportunity.

    here is the full script

    function RunProcessOnOpportunity() {
    	var parameterURL = My.oData.GetEntityRecords("My_parameter", null, "My_value", "My_name eq 'MyProcessURL'", false, null, null, null);
    		
    	var getguid =Xrm.Page.data.entity.getId();
    	var proccesId;
    	var MyvalueToSend;	
    		
    	var getAccountId = Xrm.Page.getAttribute("parentaccountid").getValue();
    	if (getAccountId != null) {
         var nameAcc = getAccountId[0].name; 
         var idAcc = getAccountId[0].id; 
         var entityTypeAcc = getAccountId[0].entityType;
    	 var idAccString = idAcc.slice(1, -1);
    	}						   			
    		
    	if (parameterURL != null && parameterURL != undefined) {
    		if (parameterURL.length > 0) {
    			if (parameterURL[0].My_value != null && parameterURL[0].My_value != undefined) {
    					URL_P = parameterURL[0].My_value;
    					
    
    					if (getAccountId){
    						
    						var AccountInfo = My.oData.GetEntityRecords("Account", null, "My_IsCustomerAccount,My_industry,My_noofemployees,AccountId", "AccountId eq (guid'" + getAccountId[0].id + "')", false, null, null, null);
    					
    						if (getAccountId != null && getAccountId[0] != null) {
    
    							   var accountId = getAccountId[0].id.replace("{", "").replace("}", "");
    							   var req = new XMLHttpRequest();
    							   
    							   req.open("GET", Xrm.Page.context.getClientUrl() + "/api/data/v8.2/accounts(" + accountId + ")?$select=My_noofemployees", true);
    							   req.setRequestHeader("OData-MaxVersion", "4.0");
    							   req.setRequestHeader("OData-Version", "4.0");
    							   req.setRequestHeader("Accept", "application/json");
    							   req.setRequestHeader("Content-Type", "application/json; charset=utf-8");
    							   req.setRequestHeader("Prefer", "odata.include-annotations=\"*\"");
    							   req.onreadystatechange = function () {
    
    								   if (this.readyState === 4) {
    									   req.onreadystatechange = null;
    
    									   if (this.status === 200) {
    										   var result = JSON.parse(this.response);
    										   
    										   MyvalueToSend = result["My_noofemployees"];
    											return GetMappedValue(MyvalueToSend);
    									   
    									   } else {
    
    										   Xrm.Utility.alertDialog(this.statusText);
    
    									   }
    								   }
    							   };
    
    							   req.send();
    
    						}
    					}
    
    				
    					$.ajax({
    					  type: "POST",
    					  contentType: "application/json; charset=utf-8",
    					  datatype: "json",
    					  url: URL_P,
    					  data: {
    						
    						"crmGUID": idAccString,
    						"name": nameAcc,
    						"countrycode": "10",
    						"employees": GetMappedValue(MyvalueToSend),
    						"industry": "50",
    						"iscustomer": AccountInfo[0].My_IsCustomerAccount
    					  }
    					}).done(function (data) {
    
                        proccesId = data.proccesId;
    					Xrm.Page.getAttribute("processcasenumber").setValue(proccesId);
    					Xrm.Page.data.entity.save();
                        alert("Your request has been created. \n\n \t\tCase number: "+proccesId);	
    					
                        });
    				
    					Xrm.Page.data.entity.save();
    				
    				}	else	{
    					
    					alert("The process fail this time :(, please contact your CRM Administrator.");
    			}
    		}
    	}
    }
    
    function GetMappedValue(MyvalueToSend) {
    		var mapTable = [
    				[1, 1],
    				[2, 51],
    				[3, 52],
    				[4, 53],
    				[5, 54],
    				[6, 55]
    		];
        return mapTable[MyvalueToSend - 1][1];
    }
  • Verified answer
    Seren S Profile Picture
    402 on at

    Hi Ville,

    It is strange because you are creating two requests in a row but the second request with $.ajax needs a parameter from the first request (XmlHttpRequest). They are async and you are not waiting for the first response to fire the second request. I made some changes at below.  Could you please consider your code in this perspective again?

    You can share the mapped value alerts on before and after if it doesn't work again.

    function RunProcessOnOpportunity() {
        var parameterURL = My.oData.GetEntityRecords("My_parameter", null, "My_value", "My_name eq 'MyProcessURL'", false, null, null, null);
    
        var getguid = Xrm.Page.data.entity.getId();
        var proccesId;
        var MyvalueToSend;
    
        var getAccountId = Xrm.Page.getAttribute("parentaccountid").getValue();
        if (getAccountId != null) {
            var nameAcc = getAccountId[0].name;
            var idAcc = getAccountId[0].id;
            var entityTypeAcc = getAccountId[0].entityType;
            var idAccString = idAcc.slice(1, -1);
        }
    
        if (parameterURL != null && parameterURL != undefined) {
            if (parameterURL.length > 0) {
                if (parameterURL[0].My_value != null && parameterURL[0].My_value != undefined) {
                    URL_P = parameterURL[0].My_value;
    
    
                    if (getAccountId) {
    
                        var AccountInfo = My.oData.GetEntityRecords("Account", null, "My_IsCustomerAccount,My_industry,My_noofemployees,AccountId", "AccountId eq (guid'" + getAccountId[0].id + "')", false, null, null, null);
    
                        if (getAccountId != null && getAccountId[0] != null) {
    
                            var accountId = getAccountId[0].id.replace("{", "").replace("}", "");
                            var req = new XMLHttpRequest();
    
                            req.open("GET", Xrm.Page.context.getClientUrl() + "/api/data/v8.2/accounts(" + accountId + ")?$select=My_noofemployees", true);
                            req.setRequestHeader("OData-MaxVersion", "4.0");
                            req.setRequestHeader("OData-Version", "4.0");
                            req.setRequestHeader("Accept", "application/json");
                            req.setRequestHeader("Content-Type", "application/json; charset=utf-8");
                            req.setRequestHeader("Prefer", "odata.include-annotations=\"*\"");
                            req.onreadystatechange = function () {
    
                                if (this.readyState === 4) {
                                    req.onreadystatechange = null;
    
                                    if (this.status === 200) {
                                        var result = JSON.parse(this.response);
    
                                        MyvalueToSend = result["My_noofemployees"];
    
                                        //************************************
                                        //This the beginning of SECOND REQUEST
                                        //************************************
                                        //return GetMappedValue(MyvalueToSend);
                                        console.log("Value for Mapping: " + MyvalueToSend);
                                        alert("Value for Mapping: " + MyvalueToSend);
                                        var employees = GetMappedValue(MyvalueToSend);
                                        console.log("Mapped Value: " + employees);
                                        alert("Mapped Value: " + employees);
    
                                        $.ajax({
                                            type: "POST",
                                            contentType: "application/json; charset=utf-8",
                                            datatype: "json",
                                            url: URL_P,
                                            data: {
    
                                                "crmGUID": idAccString,
                                                "name": nameAcc,
                                                "countrycode": "10",
                                                "employees": employees,
                                                "industry": "50",
                                                "iscustomer": AccountInfo[0].My_IsCustomerAccount
                                            }
                                        }).done(function (data) {
    
                                            proccesId = data.proccesId;
                                            Xrm.Page.getAttribute("processcasenumber").setValue(proccesId);
                                            Xrm.Page.data.entity.save();
                                            alert("Your request has been created. \n\n \t\tCase number: " + proccesId);
    
                                            //******************************************
                                            //This the last step if everything goes well
                                            //******************************************
                                            Xrm.Page.data.entity.save();
                                        });
                                    } else {
    
                                        Xrm.Utility.alertDialog(this.statusText);
    
                                    }
                                }
                            };
    
                            req.send();
    
                        }
                    }
                } else {
    
                    alert("The process fail this time :(, please contact your CRM Administrator.");
                }
            }
        }
    }
    
    function GetMappedValue(MyvalueToSend) {
        var mapTable = [
            [1, 1],
            [2, 51],
            [3, 52],
            [4, 53],
            [5, 54],
            [6, 55]
        ];
        return mapTable[MyvalueToSend - 1][1];
    }
  • Vile Andreas Rantala Profile Picture
    1,257 on at

    Thank you Seren!

Under review

Thank you for your reply! To ensure a great experience for everyone, your content is awaiting approval by our Community Managers. Please check back later.

Helpful resources

Quick Links

Introducing the 2026 Season 1 community Super Users

Congratulations to our 2026 Super Stars!

Meet the Microsoft Dynamics 365 Contact Center Champions

We are thrilled to have these Champions in our Community!

Congratulations to the April Top 10 Community Leaders

These are the community rock stars!

Leaderboard > 🔒一 Microsoft Dynamics CRM (Archived)

Last 30 days Overall leaderboard

Featured topics

Product updates

Dynamics 365 release plans