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

Announcements

News and Announcements icon
Community site session details

Community site session details

Session Id :
Microsoft Dynamics CRM (Archived)

how to update lookup field using WebAPI ?

(0) ShareShare
ReportReport
Posted on by 235

For an account I m trying to populate primarycontactid (lookup field) using the following code but CRM returns error "400 Bad Request"

Can you please guide how is this code wrong ? Or please if can provide a working sample of similar snario ?

var entity = {};
entity.primarycontactid = {
            Id: "ba121cbc-6a41-e611-80e0-c4346bc58294",
            LogicalName: "contact"
        };

var req = new XMLHttpRequest();
req.open("PATCH", Xrm.Page.context.getClientUrl() + "/api/data/v8.0/accounts(bf121cbc-6a41-e611-80e0-c4346bc58294)", 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.onreadystatechange = function () {
    if (this.readyState === 4) {
        req.onreadystatechange = null;
        if (this.status === 204) {
            //Success - No Return Data - Do Something
        }
        else {
            alert(this.statusText);
        }
    }
};
req.send(JSON.stringify(entity));


 

*This post is locked for comments

I have the same question (0)
  • Verified answer
    Guido Preite Profile Picture
    54,086 Moderator on at

    follow this blog post in order to see how you need to specify a lookup field with the new Web API

    www.inogic.com/.../set-values-of-all-data-types-using-web-api-in-dynamics-crm

  • umma Profile Picture
    235 on at

    Thanks Guido, it helped.

    I tried as suggested using JS and result was same error, then I tried using JQuery and it was fine. Just curiest is it something known ? WebAPI sdk has not been released officially does it means it is not stable yet ? Thanks for your guidance.

  • Guido Preite Profile Picture
    54,086 Moderator on at

    jQuery is just a wrapper of JavaScript functions in order to be cross-browser compatible.

    WebAPI is officially released but not all the SDK operations are available with WebAPI yet.

    hope it helps

  • Suggested answer
    Bangar Raju Profile Picture
    15 on at

    While creating CRM record using Web Api we need to use Odata CRM Schema Names not name of the attribute.

    ie, if the field is created with name "new_accountname" then the Schema name is looks like "new_AccountName".

             So While setting lookup value we need to follow the below syntax instead of using auto code generated by CRMRestBuilder.

    Ex:

    var entity = {};

    entity["primarycontactid@odata.bind"] ="/contacts(89153C7D-E45E-E611-80F6-1458D05A5490)"

    entity["new_AccountName@odata.bind"] ="/contacts(89153C7D-E45E-E611-80F6-1458D05A5490)"

    var req = new XMLHttpRequest();

    req.open("PATCH", Xrm.Page.context.getClientUrl() + "/api/data/v8.0/accounts(bf121cbc-6a41-e611-80e0-c4346bc58294)", 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.onreadystatechange = function () {

       if (this.readyState === 4) {

           req.onreadystatechange = null;

           if (this.status === 204) {

               //Success - No Return Data - Do Something

           }

           else {

               alert(this.statusText);

           }

       }

    };

    req.send(JSON.stringify(entity));

  • Maksym Tomyn Profile Picture
    30 on at

    How to update lookup field to null ? Can I update the entity with removal of value?

    var entity = {};

    entity["primarycontactid@odata.bind"] ="/contacts(null)"

    entity["new_AccountName@odata.bind"] ="/contacts(89153C7D-E45E-E611-80F6-1458D05A5490)"

    var req = new XMLHttpRequest();

    req.open("PATCH", Xrm.Page.context.getClientUrl() + "/api/data/v8.0/accounts(bf121cbc-6a41-e611-80e0-c4346bc58294)", 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.onreadystatechange = function () {

       if (this.readyState === 4) {

           req.onreadystatechange = null;

           if (this.status === 204) {

               //Success - No Return Data - Do Something

           }

           else {

               alert(this.statusText);

           }

       }

    };

    req.send(JSON.stringify(entity));

  • Suggested answer
    tw0sh3ds Profile Picture
    5,600 on at

    @Maksym Tomyn no you have to do disassociate to remove the lookup value (https://msdn.microsoft.com/en-us/library/mt607875.aspx):

    For a single-valued navigation property, remove the $id query string parameter.

    DELETE [Organization URI]/api/data/v8.2/opportunities(00000000-0000-0000-0000-000000000001)/customerid_account/$ref HTTP/1.1
    Accept: application/json
    OData-MaxVersion: 4.0
    OData-Version: 4.0
  • Maksym Tomyn Profile Picture
    30 on at

    Do I have to create two requests of DELETE for updating of the first field and PATCH for updating of the second field?

  • Suggested answer
    tw0sh3ds Profile Picture
    5,600 on at

    You have to do two requests, but WebAPI supports batch requests, so you can do both requests in single HTTP call. Search for CRM 2016 WebAPI batch requests on google for some tutorials

  • slx Profile Picture
    386 on at

    Could you please help with the following scenario ? I am running this code to delete a reference parentcustomerid_account

    This is working successfully on DEV but when executed on different environment IFD / ADFS the request is 404 NOT FOUND

    Do you have any idea ? Thank you

    // [Org URI]/api/data/v8.2/contacts([contactid#])/parentcustomerid_account/$ref

    contact1Uri = httpClient.BaseAddress + web_api + "contacts(" + myReader.Value.ToString().ToLower() + ")/parentcustomerid_account/$ref";

    HttpResponseMessage disassocResponse1 = await httpClient.DeleteAsync(contact1Uri);

    if (disassocResponse1.StatusCode == HttpStatusCode.NoContent)

  • slx Profile Picture
    386 on at

    Could you please help with the following scenario ? I am running this code to delete a reference parentcustomerid_account

    This is working successfully on DEV but when executed on different environment IFD / ADFS the request is 404 NOT FOUND

    Do you have any idea ? Thank you

    // [Org URI]/api/data/v8.2/contacts([contactid#])/parentcustomerid_account/$ref

    contact1Uri = httpClient.BaseAddress + web_api + "contacts(" + myReader.Value.ToString

    ().ToLower() + ")/parentcustomerid_account/$ref";

    HttpResponseMessage disassocResponse1 = await httpClient.DeleteAsync(contact1Uri);

    if (disassocResponse1.StatusCode == HttpStatusCode.NoContent)

    Status code is 404 = NOT FOUND

    Same code is successful on different environment

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

Season of Sharing Community Challenge Launch!

Jump in, show your community spirit, and win prizes!

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)

#1
ScottDurow Profile Picture

ScottDurow 2

#2
GJones Profile Picture

GJones 1

Last 30 days Overall leaderboard

Featured topics

Product updates

Dynamics 365 release plans