Working with HTML web resources in Dynamics 365 is a common way to extend forms, capture user input, and interact directly with Microsoft Dataverse data. In this tutorial, we will show how to retrieve a record ID from URL parameters and then use OData calls to fetch(Read) and Create / Update / Delete records.
1. Create an HTML Web Resource
- In Dynamics 365, go to Settings > Customization > Customize the System.
- Create a new Web Resource of type HTML.
- Insert your JavaScript code within
<script>
tags.
2. Pass Parameters to the Web Resource
- Add the web resource to a form.
- In the Custom Parameters (Data) field, specify JSON data (e.g.,
{"recordId":"<recordid>"}
) so it can be parsed by the HTML.
3. Retrieve the Record ID in JavaScript
document.addEventListener("DOMContentLoaded", async function ()
{
const dataParam = getParameterByName("data");
if (dataParam) {
try {
const parsedData = JSON.parse(dataParam);
classId = parsedData.recordId ? parsedData.recordId.replace(/{|}/g, "") : null;
} catch (error) {
console.error("Error parsing data parameter:", error);
}
}
clientURL = window.location.origin;
if (classId) {
await loadParticipantsAndCourses(classId);
} else {
displayErrorMessage("No Class ID provided. Please ensure you are accessing this page with a valid Class ID.");
}
});
function getParameterByName(name)
{
name = name.replace(/[[\]]/g, "\\$&");
let regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
results = regex.exec(window.location.href);
if (!results) return null;
if (!results[2]) return '';
return decodeURIComponent(results[2].replace(/\+/g, " "));
}
4. Fetch Data from Dataverse
async function fetchFromDataverse(entity, query)
{
const requestUrl = `${clientURL}/api/data/v9.2/${entity}?${query}`;
try {
const response = await fetch(requestUrl, {
method: 'GET',
headers: {
'OData-MaxVersion': '4.0',
'OData-Version': '4.0',
'Accept': 'application/json',
'Content-Type': 'application/json; charset=utf-8',
'Prefer': 'odata.include-annotations="*"'
},
credentials: 'include'
});
if (response.ok) {
return await response.json();
} else {
console.error('Failed to load data:', response.statusText);
}
} catch (error) {
console.error('Error fetching data:', error);
}
}
5. Create Data in Dataverse
async function createRecord(entityName, data)
{
const requestUrl = `${clientURL}/api/data/v9.2/${entityName}`;
try {
const response = await fetch(requestUrl, {
method: 'POST',
headers: {
'OData-MaxVersion': '4.0',
'OData-Version': '4.0',
'Accept': 'application/json',
'Content-Type': 'application/json; charset=utf-8'
},
credentials: 'include',
body: JSON.stringify(data)
});
if (!response.ok) {
const errorResponse = await response.json();
throw new Error(`${errorResponse.error.message}`);
}
} catch (error) {
console.error('Error creating record:', error);
throw error;
}
}
6. Delete Data in Dataverse
async function deleteRecord(entityName, recordId)
{
const requestUrl = `${clientURL}/api/data/v9.2/${entityName}(${recordId})`;
try {
const response = await fetch(requestUrl, {
method: 'DELETE',
headers: {
'OData-MaxVersion': '4.0',
'OData-Version': '4.0',
'Accept': 'application/json'
},
credentials: 'include'
});
if (!response.ok) {
const errorResponse = await response.json();
throw new Error(`Failed to delete record: ${errorResponse.error.message}`);
}
} catch (error) {
console.error('Error deleting record:', error);
throw error;
}
}
7. Update Data in Dataverse
async function updateRecord(entityName, recordId, data)
{
const requestUrl = `${clientURL}/api/data/v9.2/${entityName}(${recordId})`;
try {
const response = await fetch(requestUrl, {
method: 'PATCH',
headers: {
'OData-MaxVersion': '4.0',
'OData-Version': '4.0',
'Accept': 'application/json',
'Content-Type': 'application/json; charset=utf-8'
},
credentials: 'include',
body: JSON.stringify(data)
});
if (!response.ok) {
const errorResponse = await response.json();
throw new Error(`Failed to update Training Card Status: ${errorResponse.error.message}`);
}
} catch (error) {
console.error('Error updating record:', error);
throw error;
}
}
No comments:
Post a Comment