Thursday, January 2, 2025

JavaScript Cheat Sheet for Power Apps, Databases, and Dynamics 365 Development

JavaScript Cheat Sheet

JavaScript Cheat Sheet for Power Apps, Dataverse, and Dynamics 365 Development

Table of Contents

Introduction

JavaScript is a vital component in extending and customizing Microsoft Power Apps, Dataverse, and Dynamics 365. This cheat sheet aims to provide a collection of commonly used scripts, ranging from basic to advanced, to streamline your development process.

Easy Level Scripts

1. Displaying Alert Messages

function showAlertMessage(context) {
    alert("This is a simple alert message!");
}

2. Hiding/Showing Fields or Sections

function toggleFieldVisibility(context) {
    const formContext = context.getFormContext();
    formContext.getControl("field_name").setVisible(false);
}

3. Setting Default Values

function setDefaultValue(context) {
    const formContext = context.getFormContext();
    formContext.getAttribute("field_name").setValue("Default Value");
}

4. Retrieving Field Values

function getFieldValue(context) {
    const formContext = context.getFormContext();
    const value = formContext.getAttribute("field_name").getValue();
    console.log("Field Value: ", value);
}

Intermediate Level Scripts

5. Formatting Fields

function formatField(context) {
    const formContext = context.getFormContext();
    const control = formContext.getControl("field_name");
    control.setNotification("Invalid format!", "uniqueId");
}

6. Real-time Data Validation

function validateField(context) {
    const formContext = context.getFormContext();
    const value = formContext.getAttribute("field_name").getValue();
    if (!value || value.length < 5) {
        alert("The value must be at least 5 characters long!");
    }
}

7. Filtering Option Sets Dynamically

function filterOptionSet(context) {
    const formContext = context.getFormContext();
    const options = formContext.getControl("optionset_name").getOptions();
    options.forEach(option => {
        if (option.value !== desiredValue) {
            formContext.getControl("optionset_name").removeOption(option.value);
        }
    });
}

8. Triggering Workflows with JavaScript

function triggerWorkflow(recordId, workflowId) {
    const request = new XMLHttpRequest();
    const url = `/api/data/v9.2/workflows(${workflowId})/Microsoft.Dynamics.CRM.ExecuteWorkflow`;

    request.open("POST", url, true);
    request.setRequestHeader("OData-Version", "4.0");
    request.setRequestHeader("Content-Type", "application/json; charset=utf-8");
    request.setRequestHeader("Accept", "application/json");

    const data = JSON.stringify({ EntityId: recordId });
    request.send(data);
}

Advanced Level Scripts

9. Using Web API for CRUD Operations

function createRecord() {
    const data = {
        name: "New Record",
        description: "Created via JavaScript"
    };

    Xrm.WebApi.createRecord("entity_name", data).then(
        (response) => {
            console.log("Record created with ID: ", response.id);
        },
        (error) => {
            console.error("Error creating record: ", error);
        }
    );
}

10. Custom Ribbon Button Functionality

function ribbonButtonAction(primaryControl) {
    const recordId = primaryControl.data.entity.getId();
    alert(`Ribbon button clicked for record ID: ${recordId}`);
}

Best Practices

  • Always Comment Your Code: Make your scripts maintainable and easier to understand.
  • Use Try-Catch for Error Handling: Ensure robust error management.
  • Avoid Hardcoding: Use environment variables or configuration entities.
  • Test Thoroughly: Validate your scripts in different scenarios and environments.
  • Follow Naming Conventions: Use meaningful names for fields, functions, and variables.

No comments:

Post a Comment

Power Automate Optimization: Filter Rows vs Trigger Conditions - When and Why to Use Each

Filter Rows vs Trigger Conditions in Power Automate Filter Rows vs Trigger Conditions in Power Automate Why your flow...