moussa-e
8/16/2016 - 7:58 AM

CRM 2016 #Subgrids #JavaScript #CRM2016 #MoussaElAnnan #Xrm

CRM 2016 #Subgrids #JavaScript #CRM2016 #MoussaElAnnan #Xrm

//Use this method to remove event handlers from the GridControl OnLoad event.
var myContactsGridOnloadFunction = function () { console.log("Contacts Subgrid OnLoad occurred") };
Xrm.Page.getControl("Contacts").addOnLoad(myContactsGridOnloadFunction);
Xrm.Page.getControl("Contacts").removeOnLoad(myContactsGridOnloadFunction);
 attachLoadEventToGrids = function () {

    var funtionName = "onLoad";
    try {

        //setting timeout beacuse subgid take some time to load after the form is loaded
        setTimeout(function () {

            //validating to check if the sub grid is present on the form
            if (Xrm.Page != null && Xrm.Page != undefined && Xrm.Page.getControl("PERSON_POI") != null && Xrm.Page.getControl("PERSON_POI") != undefined) {

                //stores the row count of subgrid on load event of CRM Form
                _rowCount = Xrm.Page.getControl("PERSON_POI").getGrid().getTotalRecordCount();

                //registering refreshform function onload event of subgrid
                Xrm.Page.getControl("PERSON_POI").addOnLoad(onGridLoad);
            }
        }, 5000);

    } catch (e) {

        Xrm.Utility.alertDialog(functionName + "Error: " + (e.message || e.description));

    }

}

 onGridLoad = function() {
    var functionName = " onGridLoad ";
    var currentRowCount = null;
    var randomText = generateRandomString();
    try {

        //setting timeout beacuse subgrid take some time to load after the form is loaded
        setTimeout(function () {

            //validating to check if the sub grid is present on the form
            if (Xrm.Page != null && Xrm.Page != undefined && Xrm.Page.getControl("PERSON_POI") != null && Xrm.Page.getControl("PERSON_POI") != undefined) {

                //stores the row count of subgrid on load event of CRM Form
                currentRowCount = Xrm.Page.getControl("PERSON_POI").getGrid().getTotalRecordCount();

                if (currentRowCount > _rowCount) {
                    //call the intended function which we want to call only when records are added to the grid
                    Xrm.Page.getAttribute("bd_pluginstatus").setValue(randomText);

                    //set current row count to the global row count
                    _rowCount = currentRowCount;
                    Xrm.Page.data.entity.save();
                }
                else if (currentRowCount < _rowCount) {

                    //call the intended function which we want to call only when records are removed from the grid
                    Xrm.Page.getAttribute("bd_pluginstatus").setValue(randomText);
                    //set current row count to the global row count
                    _rowCount = currentRowCount;
                    Xrm.Page.data.entity.save();
                }
            }
        }, 2000);

    } catch (e) {

        Xrm.Utility.alertDialog(functionName + "Error: " + (e.message || e.description));

    }
}
//Use this method to add event handlers to the GridControl OnLoad event.
Xrm.Page.getControl("Contacts").addOnLoad(myContactsGridOnloadFunction);
var myContactsGridOnloadFunction = function() {
 console.log("Contacts Subgrid OnLoad occurred");
};
//Use this method to get access to the ViewSelector available for the GridControl.
var contactsSubgridViewSelector = Xrm.Page.getControl("Contacts").getViewSelector();

//Use this method to get a reference to the current view.
var currentView = Xrm.Page.getControl("Contacts").getViewSelector().getCurrentView();

//Use this method to set the current view.
var ContactsIFollow = {
 entityType: 1039, // SavedQuery
 id:"{3A282DA1-5D90-E011-95AE-00155D9CFA02}", 
 name: "Contacts I Follow"
};
//Set the view using ContactsIFollow
Xrm.Page.getControl("Contacts").getViewSelector().setCurrentView(ContactsIFollow);
//Returns the total number of records that match the filter criteria of the view, not limited by the number visible in a single page.
var filteredRecordCount = Xrm.Page.getControl("Contacts").getGrid().getTotalRecordCount();
//Returns a collection of every selected GridRow in the Grid.
//Get an array of entity references for all selected rows in the subgrid
var selectedEntityReferences = [];
var selectedRows = Xrm.Page.getControl("Contacts").getGrid().getSelectedRows();
selectedRows.forEach(function (selectedRow, i) {
 selectedEntityReferences.push(selectedRow.getData().getEntity().getEntityReference());
});
//Returns a collection of every GridRow in the Grid.
var allRows = Xrm.Page.getControl("Contacts").getGrid().getRows();
//Returns the primary attribute value for the record in the row.
var firstEntityPrimaryAttributeValue = Xrm.Page.getControl("Contacts").getGrid().getRows().get(0).getData().getEntity().getPrimaryAttributeValue();
// firstEntityPrimaryAttributeValue == "Rene Valdes (sample)"
//Returns the GridRowData for the GridRow.
var allGridRowData = [];
var rows = Xrm.Page.getControl("Contacts").getGrid().getRows();
rows.forEach(function (row, i) {
 allGridRowData.push(row.getData());
});
//Use this method to get access to the Grid available in the GridControl.
var contactsSubgridGrid = Xrm.Page.getControl("Contacts").getGrid();
//Gets the entityreference.
var firstEntityReference = Xrm.Page.getControl("Contacts").getGrid().getRows().get(0).getData().getEntity().getEntityReference();
// firstEntityReference.entityType == "contact"
// firstEntityReference.id == "{13CD16BD-3EC4-E411-80CF-00155DB58496}"
// firstEntityReference.name == "Rene Valdes (sample)"
//Use this method to get the logical name of the entity data displayed in the grid.
var opportunitySubgrids = Xrm.Page.getControl(function (ctrl, i) {
 if (ctrl.getControlType() == "subgrid") {
  return (ctrl.getEntityName() == "opportunity");
 }
 else {
  return false;
 }
});
var firstEntityType = Xrm.Page.getControl("Contacts").getGrid().getRows().get(0).getData().getEntity().getEntityName();
//Returns the id for the record in the row.
var firstEntityId = Xrm.Page.getControl("Contacts").getGrid().getRows().get(0).getData().getEntity().getId();
// firstEntityId == "{13CD16BD-3EC4-E411-80CF-00155DB58496}"
var controlSubgrid = Xrm.Page.getControl("subgridName");
/*
 * Function that filter the subgrid.
 */
filterGrid = function () {
            var sgrid= parent.document.getElementById("sgrid");
            if (sgrid === null) {
                setTimeout(function () {
                    filterGrid();
                },
                    2000);
                return;
            }
            var fetchXml = "<fetch>" +
                "  <entity name='gen_claim' >" +
                "    <attribute name='gen_name' />" +
                "    <filter>" +
                "      <condition attribute='gen_name' operator='ends-with' value='" + condition + "' />" +
                "    </filter>" +
                "  </entity>" +
                "</fetch>";
            if (sgrid.control !== null) {
                sgrid.control.SetParameter("fetchXml", fetchXml);
                sgridClaims.control.Refresh();
                addOnChangeEventHandler(sgrid);
            } else {
                setTimeout(filterGrid, 2000);
            }
        }
/*
 * Function that adds onselectionchange event handler to the grid policies.
 */
addOnChangeEventHandler = function (sgrid) {
    var selectedId = undefined;
    //attach hander to the event
    sgrid.control.add_onSelectionChange(function (sender) {
        if (sender.get_selectedIds()[0] === undefined || sender.get_selectedIds()[0] === selectedId) {
            return;
        }
        //alert(sgrid.control.get_totalRecordCount());
        // selected record is returned as an object
        var selectedRecord = sender.get_selectedRecords()[0];
        // This can now be used to set a lookup's value dynamically and cause a quick form to refresh
        var lookup = [];
        lookup[0] = {}
        lookup[0].id = selectedRecord.Id;
        lookup[0].entityType = selectedRecord.TypeName;
        lookup[0].name = selectedRecord.Name;
    });
}

/*
* Function that get the subgrid total record count.
*/
function getGridTotalRecordCount() {
var subgridName = "mySubGrid";
    try {
        setTimeout(function () {
            if (Xrm.Page !== null && Xrm.Page !== undefined 
                                  && Xrm.Page.getControl(subgridName) !== null 
                                  && Xrm.Page.getControl(subgridName) !== undefined) {
            var  rowsCount = Xrm.Page.getControl(subgridName).getGrid().getTotalRecordCount();
             alert(rowsCount);
            }
        }, 4000);

    } catch (e) {

        Xrm.Utility.alertDialog(functionName + "Error: " + (e.message || e.description));
    }
}