Search code examples
javascriptdynamics-crmdynamics-365

Dynamics 365: Javascript retrieveRecord function to retrieve value and name from lookup field


I use retrieveRecord function to retrieve lookup values from a lookup and then assign the values to other lookup fields.

 var result = Xrm.WebApi.retrieveRecord(sellTo[0].entityType, customerId, '?$select=name,_kk_paymentterms_value,_kk_shippingmethod_value,_kk_freightterms_value');
        paymentTerms = result._kk_paymentterms_value;
        shippingMethod = result._kk_shippingmethod_value;
        freightTerms = result._kk_freightterms_value;

I need names to set values to lookup fields, how can I retrieve them?


Solution

  • You can add a Prefer header value to your request:

    GET [Organization URI]/api/data/v9.2/contacts?$top=100
    &$select=fullname,_parentcustomerid_value,statuscode,createdon
    &$filter=firstname eq 'henk' and lastname eq 'boeijen' and _parentcustomerid_value ne null
    
    Accept: application/json  
    OData-MaxVersion: 4.0  
    OData-Version: 4.0
    Prefer: odata.include-annotations="OData.Community.Display.V1.FormattedValue"
    

    Now the (localized) display values are added to the response for options, booleans, lookups, dates etc.

    {
      "@odata.context": "[Organization URI]/api/data/v9.2.23084.206/$metadata#contacts(fullname,_parentcustomerid_value,statuscode,createdon)",
      "value": [
        {
          "@odata.etag": "W/\"831620324\"",
          "fullname": "Boeijen, Henk van",
          "_parentcustomerid_value@OData.Community.Display.V1.FormattedValue": "My Company Name",
          "_parentcustomerid_value": "d96679fb-0e61-ed11-9561-0022487fe2b5",
          "statuscode@OData.Community.Display.V1.FormattedValue": "Active",
          "statuscode": 1,
          "createdon@OData.Community.Display.V1.FormattedValue": "28-10-2022 11:17",
          "createdon": "2022-10-28T09:17:55Z",
          "contactid": "e8ef9664-a152-ed11-bba1-0022487feed1"
        }
      ]
    }
    

    See also Query data using the Web API: Formatted values - MS Learn.