Record Creation for N:N Relationships in Dynamics 365 with JavaScript and Custom Plugins

 This comprehensive guide provides a detailed approach to automate the creation of many-to-many (N:N) relationship records in Dynamics 365 using a custom plugin and a JavaScript action. The solution streamlines the association of multiple records through a straightforward interface, making it indispensable in scenarios requiring batch processing or integration tasks.

Overview

Dynamics 365 supports complex data models, including many-to-many (N:N) relationships between entities. Automating the process of record association within these relationships not only saves time but also reduces potential errors in data management. This article details the creation of a custom plugin and a corresponding JavaScript action that triggers the plugin to facilitate these associations dynamically.

Custom Plugin: CreateNNAssociations

The CreateNNAssociations plugin automates the association of records based on a specified N

relationship. It leverages Dynamics 365's AssociateRequest to link multiple related records to a primary record dynamically.

Plugin Code:

using System;
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Query;

namespace GeneralFunctions.Plugins
{
    public class CreateNNAssociations : IPlugin
    {
        public void Execute(IServiceProvider serviceProvider)
        {
            IPluginExecutionContext context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));
            if (context.MessageName.ToLower() != "associate") return;

            EntityReference primaryRecord = (EntityReference)context.InputParameters["PrimaryRecord"];
            EntityCollection relatedRecords = (EntityCollection)context.InputParameters["RelatedRecords"];
            string relationshipSchemaName = (string)context.InputParameters["RelationshipSchemaName"];

            IOrganizationServiceFactory serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
            IOrganizationService service = serviceFactory.CreateOrganizationService(context.UserId);

            AssociateRequest associateRequest = new AssociateRequest
            {
                Target = primaryRecord,
                Relationship = new Relationship(relationshipSchemaName),
                RelatedEntities = new EntityReferenceCollection(relatedRecords.Entities)
            };

            try
            {
                service.Execute(associateRequest);
                context.OutputParameters["Result"] = true;
                context.OutputParameters["Message"] = "Association created successfully.";
            }
            catch (Exception ex)
            {
                context.OutputParameters["Result"] = false;
                context.OutputParameters["Message"] = "Error creating association: " + ex.Message;
                throw new InvalidPluginExecutionException("An error occurred while creating associations.", ex);
            }
        }
    }
}


Action:



Input Parameters:

  1. PrimaryRecord (EntityReference): Specifies the primary entity involved in the relationship.
  2. RelatedRecords (EntityCollection): Lists the entities to associate with the primary entity.
  3. RelationshipSchemaName (string): Indicates the schema name of the relationship to utilize.

Output Parameters:

  1. Result (bool): Indicates the success or failure of the association operation.
  2. Message (string): Provides feedback about the operation's outcome.

JavaScript: Triggering the Plugin

To facilitate the plugin's operation directly from the Dynamics 365 UI, a JavaScript function can be employed to collect necessary records and initiate the plugin via an action.

JavaScript Code:

function associateProductsWithParent(primaryControl, selectedProducts)
{
    var parentProductId = primaryControl.data.entity.getId().replace("{", "").replace("}", "");
    var actionName = "dsl_CreateRecordForNNRelationship";

    var relatedRecords = selectedProducts.map(function(product) {
        return {
            "@odata.type": "Microsoft.Dynamics.CRM.product",
            "productid": product.id.replace("{", "").replace("}", "")
        };
    });

    var request = {
        "PrimaryRecord": {
            "@odata.type": "Microsoft.Dynamics.CRM.EntityReference",
            "entityType": "product",
            "id": parentProductId
        },
        "RelatedRecords": relatedRecords,
        "RelationshipSchemaName": "dsl_stream",
        getMetadata: function () {
            return {
                boundParameter: null,
                parameterTypes: {
                    "PrimaryRecord": { typeName: "Microsoft.Dynamics.CRM.EntityReference", structuralProperty: 5 },
                    "RelatedRecords": { typeName: "Collection(Microsoft.Dynamics.CRM.EntityReference)", structuralProperty: 5 },
                    "RelationshipSchemaName": { typeName: "Edm.String", structuralProperty: 1 }
                },
                operationType: 0,
                operationName: actionName
            };
        }
    };

    Xrm.WebApi.online.execute(request).then(
        function success(response) {
            console.log("Associations created successfully!");
        },
        function error(error) {
            console.error("Error executing action: " + error.message);
        }
    );
}

Note: 1. RelationshipSchemaName:

Conclusion

By combining the power of a custom Dynamics 365 plugin with a JavaScript action, organizations can automate the management of N:N relationships efficiently. This solution not only facilitates data integrity and operational efficiency but also enhances the user experience by providing a seamless interface for complex data interactions.



No comments:

Post a Comment