Thursday, May 29, 2014

JavaScript to Pull Information from SubGrid on CRM Form to Text Field

I had a need to pull information from a subgrid into a text field. With CRM 2011’s limit on 62 fields for a Mail Merge and the need to input related entity information in there as well, I needed to make one field contain the information. So I created a text field to hold information and thus I needed a JavaScript to fill the field in with the information. So I have a subgrid of a many to many relationship on one of my forms, and that has all the information I need to put in the information in my text field I will be using for the mail marge. I did a lot of searching on the web, and I couldn’t really find what I was looking for. I did come across this post that helped immensely. This code helped me get to my final solution.

function SubGridLookup()
{
                // Load Subgrid from page
                var subgrid = Xrm.Page.ui.controls.get('SubGridName')._control;
                var ids = subgrid.get_innerControl();
               
                // Pull all GUIDs for lookup
                ids = ids.get_allRecordIds();

                // Setup Variables
                var cellValue;
                var fldValue = "";
                var expat = Xrm.Page.getAttribute("mailmergefieldname");
               
                // For each GUID given pull the name of the entity and add it to fldvalue
                for(i = 0; i < ids.length; i++) {

                                cellValue = subgrid.get_innerControl().getCellValue('fieldname', ids[i]);
                                fldValue = fldValue+ "- " + cellValue + "\n";
               
                } // for

                // Set field with the new field value
                expat.setValue(fldValue);          
               
} // SubGridLookup

So to step through this, first I will load the subgrid on my CRM form and then I need to get all the GUIDs of the entries in that subgrid lookup. Next I will set the values of the variables I will be using. Then we need a for loop to step through each value. We do this with the getCellValue() function on the subgrid. The key is to also invoke the get_innerControl function as well. The variables it takes is the name of the field (this is the actual field name, in my case is was from the entity it was pulling the information from) you are trying to pull and the GUID which is what you get from ids[i]. If you are having issues, figuring it out, try some alerts in there to see what you are actually pulling. I then take that value and concatenate it on so that I am putting each value in one variable to add at the end with the setValue command.
This then puts in my field like so…
- Value1
- Value2
- Value3
- Value4

And so on.

Hope this helps someone.

No comments:

Post a Comment