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 Microsoft Employee

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

  • azerob Profile Picture
    azerob 17 on at
    RE: Adding Opportunity Line Item to Opportunity via javaScript in Dynamics CRM

    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."

  • Emre GULCAN Profile Picture
    Emre GULCAN 2,379 on at
    RE: Adding Opportunity Line Item to Opportunity via javaScript in Dynamics CRM

    Hi azerob

    Can you share your code please?

  • azerob Profile Picture
    azerob 17 on at
    RE: Adding Opportunity Line Item to Opportunity via javaScript in Dynamics CRM

    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.

  • Community Member Profile Picture
    Community Member Microsoft Employee on at
    RE: Adding Opportunity Line Item to Opportunity via javaScript in Dynamics CRM

    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?

  • Verified answer
    Emre GULCAN Profile Picture
    Emre GULCAN 2,379 on at
    RE: Adding Opportunity Line Item to Opportunity via javaScript in Dynamics CRM

    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);


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

Announcing Our 2025 Season 1 Super Users!

A new season of Super Users has arrived, and we are so grateful for the daily…

Vahid Ghafarpour – Community Spotlight

We are excited to recognize Vahid Ghafarpour as our February 2025 Community…

Tip: Become a User Group leader!

Join the ranks of valued community UG leaders

Leaderboard

#1
André Arnaud de Calavon Profile Picture

André Arnaud de Cal... 292,516 Super User 2025 Season 1

#2
Martin Dráb Profile Picture

Martin Dráb 231,317 Most Valuable Professional

#3
nmaenpaa Profile Picture

nmaenpaa 101,156

Leaderboard

Featured topics

Product updates

Dynamics 365 release plans