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

Notifications

Announcements

No record found.

Community site session details

Community site session details

Session Id :
Microsoft Dynamics CRM (Archived)

Adding Opportunity Line Item to Opportunity via javaScript in Dynamics CRM

(0) ShareShare
ReportReport
Posted on by

I have a scenario where I need to insert Opportunity line (Opportunity Product) to Opportunity via Javascript. I have gone through the Web API Entity reference and tried to insert Opportunity product via Javascript.

var entity = {};
entity["opportunityid@odata.bind"] = "/opportunities(34fgh654-sd45-ff44-dd44-4455ggfd4fcf)";
entity["productid@odata.bind"] = "/products(asda4556-c509-e811-a843-444fd445ghj4)";

    var req = new XMLHttpRequest();
    req.open("POST", Xrm.Page.context.getClientUrl() + "/api/data/v8.2/opportunityproducts", 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) {
                var uri = this.getResponseHeader("OData-EntityId");
                var regExp = /\(([^)]+)\)/;
                var matches = regExp.exec(uri);
                var newEntityId = matches[1];
            } else {
                Xrm.Utility.alertDialog(this.statusText);
            }
        }
    };
    req.send(JSON.stringify(entity));

The Above code is not working and it's not inserting any new line Item

I modify the above code by removing Product ID reference and it works. New Opportunity Line Item is inserting without any product reference.

var entity = {};
entity["opportunityid@odata.bind"] = "/opportunities(34fgh654-sd45-ff44-dd44-4455ggfd4fcf)";

    var req = new XMLHttpRequest();
    req.open("POST", Xrm.Page.context.getClientUrl() + "/api/data/v8.2/opportunityproducts", 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) {
                var uri = this.getResponseHeader("OData-EntityId");
                var regExp = /\(([^)]+)\)/;
                var matches = regExp.exec(uri);
                var newEntityId = matches[1];
            } else {
                Xrm.Utility.alertDialog(this.statusText);
            }
        }
    };
    req.send(JSON.stringify(entity));

Any idea on how to insert Opportunity Line Item with Product reference via Javascript. Am I missing any fields here to associate the product with Opportunity Line?

Any help is appreciated.



*This post is locked for comments

I have the same question (0)
  • Verified answer
    Emre GULCAN Profile Picture
    2,379 on at

    Hi,

    You should modify your "entity" in request like below;

    var entity = {};
    entity["opportunityid@odata.bind"] = "/opportunities(OPPORTUNITY_ID)";
    entity["productid@odata.bind"] = "/products(PRODUCT_ID)";
    entity["uomid@odata.bind"] = "/uoms(UOM_ID)";
    entity["quantity"] = parseFloat(QUANTITY_VALUE);


    And also you can use CRM REST Builder solution (https://github.com/jlattimer/CRMRESTBuilder) to create webapi requests.

    If you use CRM REST Builder, your request will be like below, but it's not work on my environment.

    var entity = {};
    entity["opportunityid@odata.bind"] = "/opportunities(OPPORTUNITY_ID)";
    entity["productid@odata.bind"] = "/products(PRODUCT_ID)";
    entity["uomid@odata.bind"] = "/uoms(UOM_ID)";
    entity.quantity = parseFloat(QUANTITY_VALUE).toFixed(5);

    because of this I'm using this line;

    entity["quantity"] = parseFloat(QUANTITY_VALUE);


  • Community Member Profile Picture
    on at

    Thanks @Emre GULCAN its working now. So i missed the uomid and quantity :). Actually my purpose is to replicate product line item. Say if i add Product A with Quantity 10 , i need to split this product to 10 entries. Is there any OOB functionality available in CRM?

  • azerob Profile Picture
    17 on at

    Hi Emre GULCAN Cyber

    I have tried with your example in c# but I am getting BadRequest with this message.

    "message":"Unexpected exception from plug-in (Execute): XrmMasters.CalculateOpportunityProducts: System.NullReferenceException: Object reference not set to an instance of an object."

    I don't know why.

    Any help is appreciated.

  • Emre GULCAN Profile Picture
    2,379 on at

    Hi azerob

    Can you share your code please?

  • azerob Profile Picture
    17 on at

    Hi Emre GULCAN

    Here is the code.

    var jsonBody = new Dictionary<string, object>()
    {
    { "uomid@odata.bind", "/uoms(5b71260d-3248-e611-80d1-00155ddc4299)" },
    { "productid@odata.bind", "/products(9a9b2e45-d5d3-e811-80e5-00155d02682b)"},
    { "opportunityid@odata.bind", "/opportunities(eb166885-4fde-e911-a95a-00155d026b79)"},
    { "quantity", 1.0000000000 }
    };

    string httpUrl = "{my URL}/api/data/v8.2/opportunityproducts";
    string httpMethod = "POST";
    var url = new Uri(httpUrl);
    var method = new HttpMethod(httpMethod);
    var request = new HttpRequestMessage(method, url);
    HttpClient client = new HttpClient(new HttpClientHandler() { Credentials = new NetworkCredential("***", "***", "**") });
    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
    client.Timeout = TimeSpan.FromMilliseconds(Timeout.Infinite);
    string jsonItem = Newtonsoft.Json.JsonConvert.SerializeObject(jsonBody, Formatting.Indented);
    request.Content = new StringContent(jsonItem.ToString(), Encoding.UTF8, "application/json");

    var responseaa = client.SendAsync(request).Result;
    string responseContent = responseaa.Content.ReadAsStringAsync().Result;

    The Above code is not working and it's not inserting any new line Item.

    I am getting BadRequest with message :
    "message":"Unexpected exception from plug-in (Execute): XrmMasters.CalculateOpportunityProducts: System.NullReferenceException: Object reference not set to an instance of an object."

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

Responsible AI policies

As AI tools become more common, we’re introducing a Responsible AI Use…

Neeraj Kumar – Community Spotlight

We are honored to recognize Neeraj Kumar as our Community Spotlight honoree for…

Leaderboard > 🔒一 Microsoft Dynamics CRM (Archived)

#1
SA-08121319-0 Profile Picture

SA-08121319-0 4

#1
Calum MacFarlane Profile Picture

Calum MacFarlane 4

#3
Alex Fun Wei Jie Profile Picture

Alex Fun Wei Jie 2

Last 30 days Overall leaderboard

Featured topics

Product updates

Dynamics 365 release plans