Invoking Dynamics 365 Custom Actions from JavaScript to Trigger Plugins

 Custom actions in Dynamics 365 are a versatile tool to extend your CRM capabilities, allowing you to encapsulate complex operations into callable functions. These actions are particularly useful when you need to trigger plugins that execute server-side logic in response to client-side events. Here’s a simplified guide on how to invoke these actions from JavaScript, covering both basic and advanced scenarios.

Basic Custom Action Invocation

For simple tasks where you just need to trigger a plugin without passing any data to it, you can use a straightforward JavaScript function. This scenario is common for actions that perform generic operations, like recalculating data for a record based on existing information in the database.

Basic Invocation Example:

async function invokeCustomAction(entityType, entityId, actionName, successCallback) {
    const req = {
        entity: { entityType: entityType, id: entityId },
        getMetadata: function() {
            return {
                boundParameter: "entity",
                operationType: 0, // Indicates an action
                operationName: actionName,
                parameterTypes: {
                    "entity": {
                        "typeName": `mscrm.${entityType}`,
                        "structuralProperty": 5 // Indicates an entity type
                    }
                }
            };
        }
    };

    try {
        const response = await Xrm.WebApi.online.execute(req);
        const responseBody = await response.json();
        console.log(`${actionName} executed successfully.`);
        if (typeof successCallback === "function") {
            successCallback(responseBody);
        }
    } catch (error) {
        console.error(`Error executing ${actionName}:`, error.message);
        alert(`Error: ${error.message}`);
    }
}

Advanced Custom Action Invocation with Input Parameters

When your operation requires specific information from the client side, such as user inputs or selections, you can extend the invocation function to include input parameters. This method is essential for actions that depend on context or additional data for their logic.

Advanced Invocation Example with Input Parameters:

async function invokeCustomActionWithParams(entityType, entityId, actionName, inputParams, successCallback) {
    const req = {
        entity: { entityType: entityType, id: entityId },
        getMetadata: function() {
            return {
                boundParameter: "entity",
                operationType: 0,
                operationName: actionName,
                parameterTypes: {
                    "entity": {
                        "typeName": `mscrm.${entityType}`,
                        "structuralProperty": 5
                    },
                    ...Object.entries(inputParams).reduce((acc, [key, value]) => {
                        acc[key] = {
                            typeName: value.typeName,
                            structuralProperty: value.structuralProperty,
                            value: value.value
                        };
                        return acc;
                    }, {})
                }
            };
        }
    };

    try {
        const response = await Xrm.WebApi.online.execute(req);
        const responseBody = await response.json();
        console.log(`${actionName} executed successfully with parameters.`);
        if (typeof successCallback === "function") {
            successCallback(responseBody);
        }
    } catch (error) {
        console.error(`Error executing ${actionName} with parameters:`, error.message);
        alert(`Error: ${error.message}`);
    }
}

Example Call with Parameters:

// Sample call with input parameters
invokeCustomActionWithParams(
    "account", // Entity type
    "00000000-0000-0000-0000-000000000000", // Entity ID
    "new_YourCustomAction", // Custom action name
    {
        "ParameterName": {
            value: "Some value",
            typeName: "Edm.String",
            structuralProperty: 1 // Primitive type
        }
    },
    function(responseBody) {
        // Handle success
        console.log("Action response:", responseBody);
    }
);

Conclusion

Whether triggering simple operations without input data or complex processes requiring specific parameters, invoking custom actions from JavaScript provides a bridge to executing server-side logic from the client-side context. This approach enables a more dynamic and interactive user experience in Dynamics 365 applications.

No comments:

Post a Comment