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)

Jscript to Sum Child

(0) ShareShare
ReportReport
Posted on by

I've tried JS option for summing a child entity in quotes but i seem to have an issue and it chucks up an error. I found the code from someone else doing the same as i was trying to do. The code is as follows

function setupGridRefresh() {

var targetgrid = document.getElementById("quotedetailsGrid");

// If already loaded

if (targetgrid.readyState == 'complete') {

   targetgrid.attachEvent("onrefresh", subGridOnload);

}

else {

   targetgrid.onreadystatechange = function applyRefreshEvent() {

       var targetgrid = document.getElementById("quotedetailsGrid");

       if (targetgrid.readyState == 'complete') {

           targetgrid.attachEvent("onrefresh", subGridOnload);

       }

   }

}

subGridOnload();

}

function subGridOnload() {

//debugger;

var grid = Xrm.Page.ui.controls.get('quotedetailsGrid')._control;

var sum = 0.00;

if (grid.get_innerControl() == null) {

   setTimeout(subGridOnload, 1000);

   return;

}

else if (grid.get_innerControl()._element.innerText.search("Loading") != -1) {

   setTimeout(subGridOnload, 1000);

   return;

}

var ids = grid.get_innerControl().get_allRecordIds();

var cellValue;

for (i = 0; i < ids.length; i++) {

   if (grid.get_innerControl().getCellValue('sb_itemweight', ids[i]) != "") {

       cellValue = grid.get_innerControl().getCellValue('sb_itemweight', ids[i]);

       cellValue = cellValue.substring(2);

       cellValue = parseFloat(cellValue);

       sum = sum + cellValue;

   }

}

var currentSum = Xrm.Page.getAttribute('sb_totalowe').getValue();

if (sum > 0 || (currentSum != sum && currentSum != null)) {

   Xrm.Page.getAttribute('sb_totalowe').setValue(sum);

}

}

The error that it brings when i load the form is Cannot read property 'readyState' of null at setupgridrefresh

I have double check to make sure all the names of fields and entitys are correct and can't find any issues.

Am i doing something silly here i believe this code was for 2013 have any of the principles changed

Cheers

Dan

*This post is locked for comments

I have the same question (0)
  • Suggested answer
    tw0sh3ds Profile Picture
    5,600 on at

    Hi,

    What you are trying to achieve here is unsupported. This code indeed worked in older version of CRM, but this is what happens with unsupported code - it usually stops working after upgrade to new version of CRM. You can use Rollup fields to sum the child records value, calculate this value in plugin or retrieve all records in JS (using Web API) and sum it up in JS. I would never recommend an unsupported solution, but if you look through this forum there is somewhere version working in the latest CRM (but again - better change the design than use unsupported solutions)

    Regards,

    Pawel

  • Suggested answer
    Alagunellaikumar Profile Picture
    6,212 on at

    Hi

    Use this function subGridOnload only (no need of this setupGridRefresh) call this function in the onload event in the form properties.

  • Community Member Profile Picture
    on at

    Many Thanks for your Response

    I tried Using a rollup field but i couldn't find my custom field within the options Basicly in the sub grid on quotes i have a column call Itemweight and i would like to sum up all the values

    Regards

    Dan

  • Community Member Profile Picture
    on at

    Hi Alagu when i try you solution i get the following error

    Cannot read property 'get_innerControl' of undefined at SubGridOnLoad

    any ideas

    PS thank you for responding

    Cheers

    Dan

  • tw0sh3ds Profile Picture
    5,600 on at

    Hi Dan,

    If you could not find the field on the rollup field, it's most likely that you have some data mismatch. Please describe how are you trying to add this rollup field. What you should do is:

    1) Create a new field on your parent entity (if Itemweight is decimal than use decimal also for this rollup field)

    2) Edit this rollup field

    3) Choose the child entity (in your case Quote)

    4) Choose SUM and the attribute Itemweight (it should be there if the types are matching)

    Regards,

    Pawel

  • Suggested answer
    Ben John Profile Picture
    559 on at
    Hi Dandare,

    as the others already mentioned, you could use a roleup field.
    https://technet.microsoft.com/en-US/library/dn832162.aspx

    If you still want to use JavaScript, I recommend to use the webservice of CRM. You can use the following code as example for CRM 2016 (V8.0) and later.

    function sumItemWeigth()
    {
        var async = true,
            opptyID = Xrm.Page.data.entity.getId().replace("{", "").replace("}", ""),
            singleField = "sb_itemweight",
            sumField = "sb_totalowe";
     
        var req = new XMLHttpRequest();
        req.open("GET", Xrm.Page.context.getClientUrl() + "/api/data/v8.0/quotedetails?$select=" + singleField + "&$filter=_quoteid_value eq " + opptyID, async);
        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 === 200)
                {
                    var results = JSON.parse(this.response);
                    var totalowe = 0.0;
                    for (var i = 0; i < results.value.length; i++)
                    {
                        totalowe += parseFloat(results.value[i][singleField]);
                    }
     
                    if (totalowe > 0.0)
                    {
                        Xrm.Page.getAttribute(sumField).setValue(sum);
                        Xrm.Page.getAttribute(sumField).setSubmitMode("dirty");
                    }
                }
                else
                {
                    Xrm.Utility.alertDialog(this.statusText);
                }
            }
        };
        req.send();
    }

    BR Ben
  • Community Member Profile Picture
    on at

    Hi Ben Thank you for your response. When i Try your code all i get is

    ReferenceError: sumItemWeigth is not defined at eval

    I had this before when i tried another example. Any ideas why it would do this. I am going to have a go with the rollup field today see if i can get that working. The only issue i see is that it is a custom field and i don't think the rollup can see the Subgrid just the Quote_Product which i don't believe i can map the Item_Weight to, to get the values

    Regards

    Dan

  • Suggested answer
    tw0sh3ds Profile Picture
    5,600 on at

    Hi Dan,

    I'm assuming that ItemWeight is not on QuoteDetails but on Product? If it's on product you can just create the same field on QuoteProduct and copy it's value from related Product (by using workflow/business rule/calculated field)

  • Community Member Profile Picture
    on at

    Thank you for the reply. I was thinking about doing something like

    A workflow on entity Quote Product then when every record field change (Amount?? possibly)

    This would then run an update step to set the propities of product weight. In the set Properties tab what do i need to do

    Regards

    Dan

  • Suggested answer
    tw0sh3ds Profile Picture
    5,600 on at

    Hi Dan,

    Item weight does not seem to me like a value that changes often (if ever), so I would rather create a workflow on Create of Quote Detail

    1) Create a workflow that will run on Quote Detail create (and only create)

    2) Add Update record step

    3) Click Set properties

    4) Find the Item Weight field (I'm assuming you already added it on Quote Detail entity) - click in it

    5) on the right from drop down choose related record - it should be Product/Existing Product or whatever your Product field is called on Quote Detail

    6) from the next drop down choose Item Weight

    7) Click add and ok

    8) You should have dynamically set value in your Item Weight on Quote Detail (some text token in yellow)

    9) Save and activate your workflow

    You can make workflow as running real-time not in background if you wish to calculate this value at once after creating Quote Product

    Now this value should be copied over automatically and you can create a rollup field on that.

    You can also create a calculated field on Quote Detail - like a normal Whole Number or Decimal field but instead of simple choose Calculated. Then in options just put value as Item Weight from related Product. This is much simpler approach but you will not be able to override this value if there will be any requirement like that in the future.

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