function main(primaryControl){
//Get the list of grid records.
const girdrowList = primaryControl.getGrid().getRows().get();
//Gets the HTML element where the grid unit is located.
const labelList=[]
const divList =window.top.document.querySelectorAll("div[aria-colindex='4']");
//If the wrong column is fetched, print a message on the console and exit.
if(!divList[0].innerText.includes("Related Contacts")){
console.error(`You incorrectly got the DivHTML element in the ${divList[0].innerText} column, and should got the HTML element in the Related Contact column`)
return;
}
for(let i=1;i<divList.length;i++){
let label = divList[i].querySelector("label[aria-label='']")
labelList.push(labelabel)
}
//Creates a drop-down box for each grid cell in the column to display the related contacts information,
//if the contact information have already been obtained and the drop-down boxes have been generated then it is an update operation.
if(labelListList[0].querySelectorAll("select").length ===1){
updateData(girdrowList,labelList);
}else{
createDropdown(girdrowList,labelList);
}
}
async function createDropdown(girdrowList,labelList) {
for(let i=0;i<girdrowList.length;i++){
//Gets the ID of a record.
let ID = girdrowList[i].data.entity.getId();
//Create a drop-down box
let select = window.top.document.createElement("select");
select.style.display="block";
let label = labelList[i];
//Expands the many-to-many relationship between case and contact to get the contact records related to a record in the view grid.
await Xrm.WebApi.retrieveRecord("incident",ID,"?$expand=cr642_Contact_Incident_Incident" ).then(
function success(result) {
let contacts = result.cr642_Contact_Incident_Incident
for (var i = 0; i < contacts.length; i++) {
let option = window.top.document.createElement('option');
option.innerText = contacts[i].fullname;
select.appendChild(option);
}
label.appendChild(select);
},
function (error) {
console.log(error.message);
}
);
}
}
async function updateData(girdrowList,labelList){
for(let i=0;i<girdrowList.length;i++){
let ID = girdrowList[i].data.entity.getId();
let label = labelList[i];
let select = label.querySelector("select");
select.options.length = 0;
await Xrm.WebApi.retrieveRecord("incident",ID,"?$expand=cr642_Contact_Incident_Incident" ).then(
function success(result) {
let contacts = result.cr642_Contact_Incident_Incident;
for (var i = 0; i < contacts.length; i++) {
let option = window.top.document.createElement('option');
option.innerText = contacts[i].fullname;
select.appendChild(option);
}
label.appendChild(select);
},
function (error) {
console.log(error.message);
}
);
}
}