locked
MS CRM 2011 ONLINE - Auto populate default unit for product in order product RRS feed

  • Question

  • Any suggestions how to do that?

    When I set a product in order product form I want automatically populate the unit field with the product's default unit. I have about 50 products and every product has only one unit. Because of that it is kind of frustrating to allways manually define the unit.

    Thursday, October 3, 2013 6:10 AM

Answers

  • Problem solved.

    var oDataPath = serverUrl + "/XRMServices/2011/OrganizationData.svc";

    Above line gives something like this: <my organization url/my organization>/XRMServices/2011/OrganizationData.svc and this is the reason for 404 error.

    When I changed it to this: var oDataPath = my organization url + "/XRMServices/2011/OrganizationData.svc"; I got a correct address and everyting work now!


    • Marked as answer by crm-user-crm Friday, October 4, 2013 11:01 AM
    Friday, October 4, 2013 11:01 AM

All replies

  • Hi,

    Please refer below blog.

    http://crmuk.wordpress.com/2012/08/12/crm-2011-set-default-unit-when-selecting-a-product/

    Thanks!

    If this post helps you, please click "Mark As Answer" on the post and "Vote as Helpful"

    Thursday, October 3, 2013 6:26 AM
  • Hi,

    Please refer below blog.

    http://crmuk.wordpress.com/2012/08/12/crm-2011-set-default-unit-when-selecting-a-product/

    Thanks!

    If this post helps you, please click "Mark As Answer" on the post and "Vote as Helpful"

    "The JSON2 Javascript library must be added to the form as a webresource and set to load before this javascript library" Hmm, how I do that? I can add the library to the form, but how I set to load on before the other? What function should I call?
    Thursday, October 3, 2013 7:09 AM
  • Hi,

    To perform an ODATA call you need to add jquery1.4.1.min and json2 files in your Form Properties. You can get those files from sdk.
    path – \sdk\samplecode\js\restendpoint\jqueryrestdataoperations\jqueryrestdataoperations\scripts.

    - First deploy the JavaScript jquery1.4.1.min and json2 through Web resource in CRM.

    - Add those to form.

    You don't need to call any function of these libraries. Just add to the CRM form for which you are writing JavaScript. Please make sure both files are added on top .

    Thanks!

    Thursday, October 3, 2013 7:13 AM
  • I get this kind of error message:

    Field: productid

    Event: onchange

    Error: Acces is denied

    What is wrong?

    Thursday, October 3, 2013 8:48 AM
  • Hi,

    Please replace the line with below code.

    var serverUrl = "http://" + window.location.host + "/" + Xrm.Page.context.getOrgUniqueName();

     With

     var serverUrl =document.location.protocol + "//" + document.location.host + "/" + Xrm.Page.context.getOrgUniqueName();

    HTH!

    Thanks!

    Thursday, October 3, 2013 9:08 AM
  • Hi,

    Please replace the line with below code.

    var serverUrl = "http://" + window.location.host + "/" + Xrm.Page.context.getOrgUniqueName();

     With

     var serverUrl =document.location.protocol + "//" + document.location.host + "/" + Xrm.Page.context.getOrgUniqueName();

    HTH!

    Thanks!

    Well the error disappeared but nothing happened.
    Thursday, October 3, 2013 9:18 AM
  • I am debuggin this with alerts. The code will go to stage 8 but not stage 9 or at least the alert won't pop up:
    {
                        alert(" stage8");
                            if (this.status == 200)
                                    {
                                    alert(" stage9");
                                        var retrievedRecords = JSON.parse(retrieveReq.responseText).d;
                                        if(retrievedRecords.results.length > 0)
                                                        {
                                                        alert(" stage10");
                                                            var product = retrievedRecords.results[0];
                                                            var uomguid = product.DefaultUoMId.Id;
                                                            var uomname = product.DefaultUoMId.Name;
                                                            var uomlogical = product.DefaultUoMId.LogicalName;
                                                            alert(product+ uomguid+ uomname +uomlogical);
                                                            //Set the Unit lookup field with the value returned
                                                            Xrm.Page.getAttribute('uomid').setValue([{id: uomguid, name: uomname, entityType: uomlogical}]);
                                                        }
                                    }
                        }


    Thursday, October 3, 2013 9:27 AM
  • I debugged this.status and it gives 404.
    Thursday, October 3, 2013 9:41 AM
  • Hi,

    you can try the below code

    function getServerUrl() {
        var context, crmServerUrl;
        var isOffline = false;
    
        try {
            if (typeof GetGlobalContext != "undefined") {
                context = GetGlobalContext();
            }
            else if (typeof Xrm != "undefined") {
                context = Xrm.Page.context;
            }
            else {
                throw new Error("CRM context is not available.");
            }
    
            if (context.isOutlookClient() && !context.isOutlookOnline()) {
                crmServerUrl = window.location.protocol + "//" + window.location.host;
                isOffline;
            } else {
                crmServerUrl = context.getServerUrl();
                crmServerUrl = crmServerUrl.replace(/^(http|https):\/\/([_a-zA-Z0-9\-\.]+)(:([0-9]{1,5}))?/, window.location.protocol + "//" + window.location.host);
                crmServerUrl = crmServerUrl.replace(/\/$/, ""); // remove trailing slash if any
            }
    
            return crmServerUrl;
        }
        catch (e) {
    
            alert('getServerUrl:' + e.description);
        }
    }
    
    function SetProductUnit() {
        try {
    
            //Start building URI of rest endpoint
            var serverUrl = getServerUrl();
            //Get the value of the Product
            var productid = Xrm.Page.data.entity.attributes.get("productid").getValue()
    
            if (productid != null) {
    
                var productguid = productid[0].id;
    
                // Creating the Odata Endpoint
                var oDataPath = serverUrl + "/XRMServices/2011/OrganizationData.svc";
                var retrieveReq = new XMLHttpRequest();
                var Odata = oDataPath + "/ProductSet?$select=DefaultUoMId&$filter=ProductId eq guid'" + productguid + "'";
                retrieveReq.open("GET", Odata, false);
                retrieveReq.setRequestHeader("Accept", "application/json");
                retrieveReq.setRequestHeader("Content-Type", "application/json; charset=utf-8");
                retrieveReq.onreadystatechange = function () {
    
                    if (this.readyState == 4) {
                        if (this.status == 200) {
                            var retrievedRecords = JSON.parse(retrieveReq.responseText).d;
                            if (retrievedRecords.results.length > 0) {
                                var product = retrievedRecords.results[0];
                                var uomguid = product.DefaultUoMId.Id;
                                var uomname = product.DefaultUoMId.Name;
                                var uomlogical = product.DefaultUoMId.LogicalName;
                                //Set the Unit lookup field with the value returned
                                Xrm.Page.getAttribute("uomid").setValue([{ id: uomguid, name: uomname, entityType: uomlogical }]);
                            }
                        }
                    }
                }
    
                //Send the request
                retrieveReq.send();
            }
            else {
                //If the onchange event has been a delete of the Product or no product exists then clear the Unit field
                Xrm.Page.getAttribute("uomid").setValue(null);
            }
        } catch (e) {
            alert('SetProductUnit: ' + e.description);
        }
    }

    you need to call the "SetProductUnit" on change of the product of "order line"

    If this post answers your question, please click "Mark As Answer" on the post and "Mark as Helpful"

    Thanks !

    Subhash

    Thursday, October 3, 2013 10:12 AM
  • Hi,

    I have tried the code and it worked perfectly.Hope you have called Timer() function on change of product.

    Would you please debug the code and post the Odata value that you are getting through below line?

    var Odata = oDataPath + "/ProductSet?$select=DefaultUoMId&$filter=ProductId eq guid'" + productguid + "'";

    try to browse the path in the browser.  

    HTH!

    Thanks!

    Thursday, October 3, 2013 11:17 AM
  • Hi,

    I have tried the code and it worked perfectly.Hope you have called Timer() function on change of product.

    Would you please debug the code and post the Odata value that you are getting through below line?

    var Odata = oDataPath + "/ProductSet?$select=DefaultUoMId&$filter=ProductId eq guid'" + productguid + "'";

    try to browse the path in the browser.  

    HTH!

    Thanks!

    Hi

    This line brings list of products when set to browser:

    ...XRMServices/2011/OrganizationData.svc/ProductSet?$select=DefaultUoMId&

    This is what I get when I debug the Odata:

    ...XRMServices/2011/OrganizationData.svc/ProductSet?$select=DefaultUoMId&$filter=ProductId eq guid'{0bf65b93-30ed-e211-9b99-ee3a97cbb23b}'


    • Edited by crm-user-crm Thursday, October 3, 2013 11:59 AM typo in guid
    Thursday, October 3, 2013 11:45 AM
  • Just to be sure. This script gets a defined default unit for selected product. I have been tested this for product "wood" and there is a default unit for "wood" which is "tonne". Now if I select "oil" product and there is the unit "barrel" for "oil", this works also?
    Thursday, October 3, 2013 12:13 PM
  • Hi,

    Yes, it sets default Unit set on product. what is issue?

    This JavaScript retrieves the default unit (DefaultUoMId) set on Product and sets on order.

    If you will change the product it will change unit as well on order.

    HTH!

    Thanks!

    Thursday, October 3, 2013 12:19 PM
  • Hi,

    Yes, it sets default Unit set on product. what is issue?

    This JavaScript retrieves the default unit (DefaultUoMId) set on Product and sets on order.

    If you will change the product it will change unit as well on order.

    HTH!

    Thanks!

    No, there is no issue. I just wanted to be sure.

    Could the problem be in quotation marks? When I put javascript to CRM, I need to use this form Xrm.Page.data.entity.attributes.get('productid').getValue() instead of this Xrm.Page.data.entity.attributes.get("productid").getValue().


    Thursday, October 3, 2013 12:30 PM
  • Hi,

    It should work without any issue. in case of quotation mark issue it would have thrown error.

    If this post helps you, please click "Mark As Answer" on the post and "Vote as Helpful".

    Thursday, October 3, 2013 12:35 PM
  • Hi,

    It should work without any issue. in case of quotation mark issue it would have thrown error.

    If this post helps you, please click "Mark As Answer" on the post and "Vote as Helpful".


    How have you named your json libary in crm? Could that be the problem?
    Thursday, October 3, 2013 12:48 PM
  • The library name is never a problem. when we read something directly with form it doesn't have anything with library. These libraries are required for CRM Odata query.

    You can also get the Lookup value using below code.

    var productid =Xrm.Page.getAttribute("productid").getValue();

    HTH!

    Thanks!

    If this post helps you, please click "Mark As Answer" on the post and "Vote as Helpful". 

    Thursday, October 3, 2013 1:01 PM
  • The library name is never a problem. when we read something directly with form it doesn't have anything with library. These libraries are required for CRM Odata query.

    You can also get the Lookup value using below code.

    var productid =Xrm.Page.getAttribute("productid").getValue();

    HTH!

    Thanks!

    If this post helps you, please click "Mark As Answer" on the post and "Vote as Helpful".


    Well, still when I debug this.status, it gives 404 http error. I think that is the main problem for now.
    Friday, October 4, 2013 4:58 AM
  • Ok, more info.

    Using this ProductSet?$select=DefaultUoMId,ProductId&$filter=ProductId eq '03f65b93-30ed-e211-9b99-ee3a97cbb23b' I am getting this <?xml version="1.0" encoding="utf-8" standalone="yes"?>
    <error xmlns="http://schemas.microsoft.com/ado/2007/08/dataservices/metadata">
      <code></code>
      <message xml:lang="en-US">Operator 'eq' incompatible with operand types 'System.Guid' and 'System.String' at position 10.</message>
    </error>

    Friday, October 4, 2013 7:15 AM
  • Ok, I am using code below. It goes all the way to part "if (this.status == 200)". I have debuged this.status and it says 404. Stage 9 is never reached. Because of that I thought the Odata address is wrong. But when I set it straight to the browser it works. I am very stuck with this at the moment and any help is welcome.
    /*
    
    When a product value is changed set the Unit field to the Default Unit value specified on the Product entity
    //The JSON2 Javascript library must be added to the form as a webresource and set to load before this javascript library
    Set the Timer function to be fired onchange of the product field - this will wait for 100ms then launch the SetProductUnit function
    */
     
    function Timer()
    
    //This is the function that is fired onchange of the product field
    //A timer is required before firing the SetProductUnit function
    //More info here http://promx.wordpress.com/2011/06/27/setting-the-default-unit-for-opportunity-quote-and-salesorder-product-in-crm-2011-using-javascript/
    {
    alert("timer");
        window.setTimeout(SetProductUnit(), 100);
    }
     
    function SetProductUnit()
    //Set the Unit value to the default Unit of the product
    {
    
        //Start building URI of rest endpoint
        //var serverUrl = "http://" + window.location.host + "/" + Xrm.Page.context.getOrgUniqueName();
    	var serverUrl = document.location.protocol + "//" + document.location.host + "/" + Xrm.Page.context.getOrgUniqueName();
        //Get the value of the Product
    	
    	
        var productid = Xrm.Page.data.entity.attributes.get('productid').getValue();
    alert(productid);
    
     
        if (productid != null)
        {
     
            var productguid = productid[0].id;
     
             // Creating the Odata Endpoint
    		 alert(" stage6");
    		alert("productguid" +productguid);
    		var clear = productguid;
    		var n=clear.replace("{", "").replace("}", "");
    		alert(n);
    		 
            var oDataPath = serverUrl + "/XRMServices/2011/OrganizationData.svc";
            var retrieveReq = new XMLHttpRequest();
            var Odata = oDataPath + "/ProductSet?$select=DefaultUoMId&$filter=ProductId eq Guid'" + n + "'";
            retrieveReq.open("GET", Odata, false);
            retrieveReq.setRequestHeader("Accept", "application/json");
            retrieveReq.setRequestHeader("Content-Type", "application/json; charset=utf-8");
    		alert(Odata);
            retrieveReq.onreadystatechange = function ()
            {
    		alert(" stage7");
     
                if (this.readyState == 4)
    					alert(" stage8");
                        {
    					alert(this.status);
                            if (this.status == 200)
                                    {
    								alert(" stage9");
                                        var retrievedRecords = JSON.parse(retrieveReq.responseText).d;
                                        if(retrievedRecords.results.length > 0)
                                                        {
    													alert(" stage10");
                                                            var product = retrievedRecords.results[0];
                                                            var uomguid = product.DefaultUoMId.Id;
                                                            var uomname = product.DefaultUoMId.Name;
                                                            var uomlogical = product.DefaultUoMId.LogicalName;
    														alert(product+ uomguid+ uomname +uomlogical);
                                                            //Set the Unit lookup field with the value returned
                                                            Xrm.Page.getAttribute('uomid').setValue([{id: uomguid, name: uomname, entityType: uomlogical}]);
                                                        }
                                    }
                        }
            }
     
        //Send the request
        retrieveReq.send();
        }
        else
        {
            //If the onchange event has been a delete of the Product or no product exists then clear the Unit field
            Xrm.Page.getAttribute('uomid').setValue(null);
        }
    }

    Friday, October 4, 2013 10:26 AM
  • Problem solved.

    var oDataPath = serverUrl + "/XRMServices/2011/OrganizationData.svc";

    Above line gives something like this: <my organization url/my organization>/XRMServices/2011/OrganizationData.svc and this is the reason for 404 error.

    When I changed it to this: var oDataPath = my organization url + "/XRMServices/2011/OrganizationData.svc"; I got a correct address and everyting work now!


    • Marked as answer by crm-user-crm Friday, October 4, 2013 11:01 AM
    Friday, October 4, 2013 11:01 AM