locked
Trouble with "Use JavaScript to Update Price Per Unit When Selecting a Unit in Dynamics CRM 2011" RRS feed

  • Question

  • Hi there,

    http://www.powerobjects.com/blog/2012/11/29/use-javascript-to-update-price-per-unit-when-selecting-a-unit/

    function onChangeUnit(){

    var productField = Xrm.Page.getAttribute(‘productid’).getValue();

    var productFieldId = productField[0].id; //store the product guid here

    if (productFieldId != null)//if product not null get guid for unit

    {

    var unit = Xrm.Page.getAttribute(‘uomid’).getValue();

    //get guid for Parent opportunity

    var opportunityId = Xrm.Page.getAttribute(‘opportunityid’).getValue();

    if (opportunityId != null) //if opportunity guid is null, discontinue

    {

    //build query

    var pagecontext = Xrm.Page.context;

    var serverUrl = pagecontext.getServerUrl();

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

    var oDataSelect = oDataPath + "OpportunitySet?$select=PriceLevelId&$filter=OpportunityId eq guid’" + opportunityId + "’";

    //start AJAX call for the parent price list guid

    $.ajax({

    type: "GET",

    contentType: "application/json; charset=utf-8",

    datatype: "json",

    url: oDataSelect,

    beforeSend: function (XMLHttpRequest) { XMLHttpRequest.setRequestHeader("Accept", "application/json"); },

    success: function (data,status) { NowWeHaveThePriceList(data,status,productFieldId,unit,oDataPath);},

    error: function (XmlHttpRequest, textStatus, errorThrown) {

    alert(‘OData Select Failed: ‘ + errorThrown + ". There is no parent price list");

    }

    });

    }

    }

    }

    function NowWeHaveThePriceList(data,status,productFieldId,unit,oDataPath){

    var priceLevelId = data.d.results[0].PriceLevelId.Id; //retrieved pricelevel

    //start AJAX clal for Price List Item entities = Price List GUID and Product Guid and Unit Guid and return the Amount on that price list item. This will return one results.

    var oDataSelect2 = oDataPath + "ProductPriceLevelSet?$select=Amount&$filter=(PriceLevelId/Id eq guid’" + priceLevelId +

    "’ and ProductId/Id eq guid’"+ productFieldId + "’ and UoMId/Id eq guid’" + unit[0].id + "’)";

    $.ajax({

    type: "GET",

    contentType: "application/json; charset=utf-8",

    datatype: "json",

    url: oDataSelect2,

    beforeSend: function (XMLHttpRequest) { XMLHttpRequest.setRequestHeader("Accept", "application/json"); },

    success: NowWeHavePrice,

    error: function (XmlHttpRequest, textStatus, errorThrown) {

    alert(‘OData Select Failed: ‘+ errorThrown + ". There is no price list item for this product");

    }

    });

    }

    function NowWeHavePrice(data,status){

    if (data != null){

    //set the price per unit

    var priceListItemAmount = data.d.results[0].Amount.Value ;

    Xrm.Page.getAttribute("priceperunit").setValue(parseFloat(eval(priceListItemAmount)));

    Xrm.Page.getAttribute("priceperunit").setSubmitModeAlways;

    }

    }

    I've been trying to get the above JavaScript to work with my crm 2011 on premise with rollup 12, and it doesn't seem to work. I keep getting this error after I change the unit of my opportunity product. I added these

    jquery1.4.1.min (70.2 KB)

    json2 (17.4 KB)

    sdk.rest (22.2 KB)

    according to the instructions.

    The Error Message below appears after I change the unit:

    There was an error with the field's customized event.

    Field: uomid

    Event: onChange

    Error: 'onChangeUnit' is undefined


    all my functions i try to run from other users code seem to also return "function_name" is null or undefined. 

    the only one that works would be

                      

    if (typeof FInvoice == "undefined") {

     FInvoice = {};

    }



    FInvoice.CalculateBalance = function () {

     var payment1 = Xrm.Page.data.entity.attributes.get("new_val1").getValue();

     var payment2 = Xrm.Page.data.entity.attributes.get("baseamount").getValue();





     var payments = (FInvoice.NullCheck(payment1) * FInvoice.NullCheck(payment2)) / 100;


     Xrm.Page.data.entity.attributes.get("manualdiscountamount").setValue(payments);
      Xrm.Page.getAttribute("manualdiscountamount").setSubmitMode("always");


    }



    FInvoice.NullCheck = function (value) {

     if (value == null) {

      return 0.0;

    }

     else {

      return value;


     Xrm.Page.data.entity.save(); 



     }

    }

    help !! 



    Wednesday, February 27, 2013 3:44 AM

Answers

  • I cleaned up the code and it seemed to be working - perhaps there was a typo someplace

    function onChangeUnit() {
        var productField = Xrm.Page.getAttribute("productid").getValue();
        var productFieldId = productField[0].id; //store the product guid here
        if (productFieldId != null) //if product not null get guid for unit
        {
            var unit = Xrm.Page.getAttribute("uomid").getValue();
            //get guid for Parent opportunity
            var opportunityId = Xrm.Page.getAttribute("opportunityid").getValue();
            if (opportunityId != null) //if opportunity guid is null, discontinue
            {
                //build query
                var pagecontext = Xrm.Page.context;
                var serverUrl = pagecontext.getServerUrl();
                var oDataPath = serverUrl + "/XRMServices/2011/OrganizationData.svc/";
                var oDataSelect = oDataPath + "OpportunitySet?$select=PriceLevelId&$filter=OpportunityId eq guid'" + opportunityId + "'";
                //start AJAX call for the parent price list guid
                $.ajax({
                    type: "GET",
                    contentType: "application/json;charset=utf-8",
                    datatype: "json",
                    url: oDataSelect,
                    beforeSend: function (XMLHttpRequest) {
                        XMLHttpRequest.setRequestHeader("Accept", "application/json");
                    },
                    success: function (data, status) {
                        NowWeHaveThePriceList(data, status, productFieldId, unit, oDataPath);
                    },
                    error: function (XmlHttpRequest, textStatus, errorThrown) {
                        alert("OData Select Failed : " + errorThrown + " .There is no parent price list ");
                    }
                });
            }
        }
    }
    
    function NowWeHaveThePriceList(data, status, productFieldId, unit, oDataPath) {
        var priceLevelId = data.d.results[0].PriceLevelId.Id; //retrieved pricelevel
        //start AJAX clal for Price List Item entities = Price List GUID and Product Guid and Unit Guid and return the Amount on that price list item. This will return one results.
        var oDataSelect2 = oDataPath + "ProductPriceLevelSet?$select=Amount&$filter=PriceLevelId/Id eq guid'" + priceLevelId + "' and ProductId/Id eq guid'" + productFieldId + "' and UoMId/Id eq guid'" + unit[0].id + "'";
    
        $.ajax({
            type: "GET",
            contentType: "application/json;charset=utf-8",
            datatype: "json",
            url: oDataSelect2,
            beforeSend: function (XMLHttpRequest) {
                XMLHttpRequest.setRequestHeader("Accept", "application/json");
            },
            success: NowWeHavePrice,
            error: function (XmlHttpRequest, textStatus, errorThrown) {
                alert("OData Select Failed : " + errorThrown + " .There is no price list item for this product");
            }
        });
    
    }
    
    function NowWeHavePrice(data, status) {
        if (data != null) {
            //set the price per unit
            var priceListItemAmount = data.d.results[0].Amount.Value;
            Xrm.Page.getAttribute("priceperunit").setValue(parseFloat(eval(priceListItemAmount)));
            Xrm.Page.getAttribute("priceperunit").setSubmitModeAlways;
        }
    }


    Jason Lattimer
    My Blog -  Follow me on Twitter -  LinkedIn

    Wednesday, February 27, 2013 5:17 AM
    Moderator

All replies

  • For the script you have you do not need to include any of the other 3 web resources. On the OnChange event of the UOM field, make sure you enter: FInvoice.CalculateBalance

    This code should then work:

    if (FInvoice === undefined) {
        var FInvoice = {};
    }
    
    FInvoice.CalculateBalance = function () {
        var payment1 = Xrm.Page.data.entity.attributes.get("new_val1").getValue();
        var payment2 = Xrm.Page.data.entity.attributes.get("baseamount").getValue();
        var payments = (FInvoice.NullCheck(payment1) * FInvoice.NullCheck(payment2)) / 100;
    
        Xrm.Page.data.entity.attributes.get("manualdiscountamount").setValue(payments);
        Xrm.Page.getAttribute("manualdiscountamount").setSubmitMode("always");
    }
    
    FInvoice.NullCheck = function (value) {
        if (value == null) {
            return 0.0;
        }
        else {
            Xrm.Page.data.entity.save();
            return value;
        }
    }


    Jason Lattimer
    My Blog -  Follow me on Twitter -  LinkedIn

    Wednesday, February 27, 2013 4:17 AM
    Moderator
  • thanks for your quick reply, but i made a mistake on my question the code I attached was the only working code for me. The code I'm having trouble with is as follows

    function onChangeUnit(){

    var productField = Xrm.Page.getAttribute(‘productid’).getValue();

    var productFieldId = productField[0].id; //store the product guid here

    if (productFieldId != null)//if product not null get guid for unit

    {

    var unit = Xrm.Page.getAttribute(‘uomid’).getValue();

    //get guid for Parent opportunity

    var opportunityId = Xrm.Page.getAttribute(‘opportunityid’).getValue();

    if (opportunityId != null) //if opportunity guid is null, discontinue

    {

    //build query

    var pagecontext = Xrm.Page.context;

    var serverUrl = pagecontext.getServerUrl();

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

    var oDataSelect = oDataPath + "OpportunitySet?$select=PriceLevelId&$filter=OpportunityId eq guid’" + opportunityId + "’";

    //start AJAX call for the parent price list guid

    $.ajax({

    type: "GET",

    contentType: "application/json; charset=utf-8",

    datatype: "json",

    url: oDataSelect,

    beforeSend: function (XMLHttpRequest) { XMLHttpRequest.setRequestHeader("Accept", "application/json"); },

    success: function (data,status) { NowWeHaveThePriceList(data,status,productFieldId,unit,oDataPath);},

    error: function (XmlHttpRequest, textStatus, errorThrown) {

    alert(‘OData Select Failed: ‘ + errorThrown + ". There is no parent price list");

    }

    });

    }

    }

    }

    function NowWeHaveThePriceList(data,status,productFieldId,unit,oDataPath){

    var priceLevelId = data.d.results[0].PriceLevelId.Id; //retrieved pricelevel

    //start AJAX clal for Price List Item entities = Price List GUID and Product Guid and Unit Guid and return the Amount on that price list item. This will return one results.

    var oDataSelect2 = oDataPath + "ProductPriceLevelSet?$select=Amount&$filter=(PriceLevelId/Id eq guid’" + priceLevelId +

    "’ and ProductId/Id eq guid’"+ productFieldId + "’ and UoMId/Id eq guid’" + unit[0].id + "’)";

    $.ajax({

    type: "GET",

    contentType: "application/json; charset=utf-8",

    datatype: "json",

    url: oDataSelect2,

    beforeSend: function (XMLHttpRequest) { XMLHttpRequest.setRequestHeader("Accept", "application/json"); },

    success: NowWeHavePrice,

    error: function (XmlHttpRequest, textStatus, errorThrown) {

    alert(‘OData Select Failed: ‘+ errorThrown + ". There is no price list item for this product");

    }

    });

    }

    function NowWeHavePrice(data,status){

    if (data != null){

    //set the price per unit

    var priceListItemAmount = data.d.results[0].Amount.Value ;

    Xrm.Page.getAttribute("priceperunit").setValue(parseFloat(eval(priceListItemAmount)));

    Xrm.Page.getAttribute("priceperunit").setSubmitModeAlways;

    }

    }

    Wednesday, February 27, 2013 4:35 AM
  • I cleaned up the code and it seemed to be working - perhaps there was a typo someplace

    function onChangeUnit() {
        var productField = Xrm.Page.getAttribute("productid").getValue();
        var productFieldId = productField[0].id; //store the product guid here
        if (productFieldId != null) //if product not null get guid for unit
        {
            var unit = Xrm.Page.getAttribute("uomid").getValue();
            //get guid for Parent opportunity
            var opportunityId = Xrm.Page.getAttribute("opportunityid").getValue();
            if (opportunityId != null) //if opportunity guid is null, discontinue
            {
                //build query
                var pagecontext = Xrm.Page.context;
                var serverUrl = pagecontext.getServerUrl();
                var oDataPath = serverUrl + "/XRMServices/2011/OrganizationData.svc/";
                var oDataSelect = oDataPath + "OpportunitySet?$select=PriceLevelId&$filter=OpportunityId eq guid'" + opportunityId + "'";
                //start AJAX call for the parent price list guid
                $.ajax({
                    type: "GET",
                    contentType: "application/json;charset=utf-8",
                    datatype: "json",
                    url: oDataSelect,
                    beforeSend: function (XMLHttpRequest) {
                        XMLHttpRequest.setRequestHeader("Accept", "application/json");
                    },
                    success: function (data, status) {
                        NowWeHaveThePriceList(data, status, productFieldId, unit, oDataPath);
                    },
                    error: function (XmlHttpRequest, textStatus, errorThrown) {
                        alert("OData Select Failed : " + errorThrown + " .There is no parent price list ");
                    }
                });
            }
        }
    }
    
    function NowWeHaveThePriceList(data, status, productFieldId, unit, oDataPath) {
        var priceLevelId = data.d.results[0].PriceLevelId.Id; //retrieved pricelevel
        //start AJAX clal for Price List Item entities = Price List GUID and Product Guid and Unit Guid and return the Amount on that price list item. This will return one results.
        var oDataSelect2 = oDataPath + "ProductPriceLevelSet?$select=Amount&$filter=PriceLevelId/Id eq guid'" + priceLevelId + "' and ProductId/Id eq guid'" + productFieldId + "' and UoMId/Id eq guid'" + unit[0].id + "'";
    
        $.ajax({
            type: "GET",
            contentType: "application/json;charset=utf-8",
            datatype: "json",
            url: oDataSelect2,
            beforeSend: function (XMLHttpRequest) {
                XMLHttpRequest.setRequestHeader("Accept", "application/json");
            },
            success: NowWeHavePrice,
            error: function (XmlHttpRequest, textStatus, errorThrown) {
                alert("OData Select Failed : " + errorThrown + " .There is no price list item for this product");
            }
        });
    
    }
    
    function NowWeHavePrice(data, status) {
        if (data != null) {
            //set the price per unit
            var priceListItemAmount = data.d.results[0].Amount.Value;
            Xrm.Page.getAttribute("priceperunit").setValue(parseFloat(eval(priceListItemAmount)));
            Xrm.Page.getAttribute("priceperunit").setSubmitModeAlways;
        }
    }


    Jason Lattimer
    My Blog -  Follow me on Twitter -  LinkedIn

    Wednesday, February 27, 2013 5:17 AM
    Moderator
  • Thanks Jason! It works! I'm a javascript novice and I've been cracking my head over it for a few days.

    May I ask what program or website you used to clean up the code? 

    Wednesday, February 27, 2013 5:41 AM
  • I am using the same code, however when I debug I am getting an error. Any suggestions?

    var oDataSelect2 = oDataPath + "ProductPriceLevelSet?$select=Amount&$filter=PriceLevelId/Id eq guid'" + priceLevelId + "' and ProductId/Id eq guid'" + productFieldId + "' and UoMId/Id eq guid'" + unit[0].id + "'";

    Unable to get property '0' of undefined or null reference

    new_updateproductprice, line 39 character 5

    Tuesday, April 30, 2013 2:04 PM