Creating a Grid dynamically using HTML in Dynamics CRM to show, update and delete associated records in an entity

This post is to show how you can create a dynamic grid in MS Dynamics CRM using HTML web resource on an entity's form to show, delete and update associated records of another entity using Jquery+Odata.


Step 1: Upload Jquery.min.js file as JScript web resource on the entity form.

Step 2: Upload Json2.js file as JScript web resource on the entity form.




Step 3: Create an HTML web resource containing below code.

<html>
<head>

</head>
<body onload="loadSubjects();">
<style type="text/css">
table {
    border-collapse: collapse;
}
table, th {
    border: 2px solid black;
}
th

{
background: lightgrey;
}
td{
border: 1px solid black;
}
</style>
<!-- Script to get global context -->
<script src="ClientGlobalContext.js.aspx" type="text/javascript"></script>
<!-- Script to add required JQuery file jquery-2.1.4.min.js-->
 <script src="../WebResources/demo_NewJquery" type="text/javascript"></script>
 <!-- Script to add required Json file-->
 <script src="../WebResources/demo_Json" type="text/javascript"></script>
 <script type="text/javascript">
 <!-- Global array to collect all the id's of records-->
     var id=[];
<!-- Function to show all the subjects associated with a student-->
    function loadSubjects() {
<!-- Getting Global context-->
var context = GetGlobalContext();
<!-- Getting id of the student's record-->
        var subjectid = parent.Xrm.Page.data.entity.getId();
<!-- Call function to get all the subjects-->
        var subjects = getSubjects(subjectid);
<!-- Initialize variable to create table dynamically-->
var tableData = "";

        if (subjects != null && subjects.length > 0) {
         
            for (var i = 0; i < subjects.length; i++) {
             
                id.push(subjects[i].demo_mathsId);
                var marks = subjects[i].demo_Marks;
                var name = subjects[i].demo_name;
                if (marks != null || name!=null ) {
                    //dynamically add table data: Subject Names and their corresponding marks
                    tableData = tableData + "<tr><td><input type='text' name='subject" + i + "' id='subject" + i + "' value='" + name + "' /></td><td><input type='text' name='marks" + i + "' id='marks" + i + "' value='" + marks + "' /></td><td><input type='button' id='" + i + "' value='Save' onclick='getdata(this.id)' /></td><td><input type='button' id='" + i + "' value='delete' onclick='deletedata(this.id)' /></td></tr>";
                }
            }
            //Create HTML table
            var table = "<table id='mytable' style='font-family:Segoe UI;font-weight:normal;font-size:13px;'><tr style='height:20px'><th>Subject</th><th>Marks</th><th colspan='2' >Options</th></tr>" + tableData + "</table>";
            //Setting the table code in div whose id=info
            document.getElementById("info").innerHTML = table;
         
        }

    }
    function getSubjects(subjectid) {
//Odata query to get the marks, subject name & id of record
        var odata = "https://nj145.crm5.dynamics.com/XRMServices/2011/OrganizationData.svc/demo_mathsSet?$select=demo_Marks,demo_name,demo_mathsId&$filter=demo_SubjectId/Id eq guid'" + subjectid + "'";
        var subjects = null;
//JQuery + Ajax
        $.ajax({
            type: "GET", //Get method is used to fetch data from Dynamics CRM
            contentType: "application/json; charset=utf-8", //Type of content
            datatype: "json", //Data type
            url: odata, //write odata query here
            async: false, //To run Script synchronously set it false
            beforeSend: function (XMLHttpRequest) {
//Setting header of request
                XMLHttpRequest.setRequestHeader("Accept", "application/json");
            },
            success: function (data, textStatus, XmlHttpRequest) {
                if (data != null && data.d.results.length > 0) {
                    subjects = data.d.results;//Getting all records
                }
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
            }
        });
        return subjects; //Returning the object containing all the records

    }
    function getdata(clicked) {

        var odataSetName = "demo_mathsSet";
        var j = parseInt(clicked); // Getting the row number whose record user wants to update
//Creating an object to send the updated values into Dynamics CRM
            var demo_maths = new Object();
            demo_maths.demo_name = document.getElementById("subject" + j).value;
            demo_maths.demo_Marks = document.getElementById("marks" + j).value;
//Getting the id of the students record
            var subjectid = parent.Xrm.Page.data.entity.getId();
//Converting the object into Json format
            var jsonEntity = window.JSON.stringify(demo_maths);

            $.ajax({
                type: "POST",
                contentType: "application/json; charset=utf-8",
                datatype: "json",
                data: jsonEntity, //Json object to send the updated data
                url: "https://nj145.crm5.dynamics.com/XRMServices/2011/OrganizationData.svc/demo_mathsSet(guid'" + id[j] + "')",
                beforeSend: function (XMLHttpRequest) {

                    //Specifying this header ensures that the results will be returned as JSON.
                    XMLHttpRequest.setRequestHeader("Accept", "application/json");
                    //Specify the HTTP method MERGE to update just the changes you are submitting.
                    XMLHttpRequest.setRequestHeader("X-HTTP-Method", "MERGE");
                },
                success: function (data, textStatus, XmlHttpRequest) {
                    //alert("Updated successfully");
                },
                error: function (XmlHttpRequest, textStatus, errorThrown) {
                    if (XmlHttpRequest && XmlHttpRequest.responseText) {
                        alert("Error while updating " + odataSetName + " ; Error – " + XmlHttpRequest.responseText);
                    }
                }
            });
            parent.Xrm.Page.data.refresh(true);
    }
    function deletedata(clicked) {
        var j = parseInt(clicked); //Getting the row number which user want to delete
        $.ajax({
            type: "POST",
            contentType: "application/json; charset=utf-8",
            datatype: "json",
         
            url: "https://nj145.crm5.dynamics.com/XRMServices/2011/OrganizationData.svc/demo_mathsSet(guid'" + id[j] + "')",
            beforeSend: function (XMLHttpRequest) {

                //Specifying this header ensures that the results will be returned as JSON.
                XMLHttpRequest.setRequestHeader("Accept", "application/json");
                //Specify the HTTP method MERGE to update just the changes you are submitting.
                XMLHttpRequest.setRequestHeader("X-HTTP-Method", "DELETE");
            },
            success: function (data, textStatus, XmlHttpRequest) {
                //alert("Updated successfully");
            },
            error: function (XmlHttpRequest, textStatus, errorThrown) {
                if (XmlHttpRequest && XmlHttpRequest.responseText) {
                    alert("Error while updating " + odataSetName + " ; Error – " + XmlHttpRequest.responseText);
                }
            }
        });
        parent.Xrm.Page.data.refresh(true);
    }
     
 
     
    </script>
<!-- Div in which the Grid is added Dynamically -->
    <div id="info"></div>
 
</body>
</html>

Note: Write the code in SOURCE tab of the HTML web resource and not in RICH TEXT

Step 4: Add web resource on the form.


Comments

Popular posts from this blog