Dynamics CRM Javascript

Dynamics 365 – Sub grid Add Existing Look up View N:N

Requirement:

When I click Add Existing button on the subgrid want to see only records based on the view.

 

Subgrid N:N relationship

Steps to be followed.

1.Create a N:N relationship of the entity.

2.Using that N:N relationship add a subgrid on the form.

3.Created a javascript file.Add the below code to it.Save and Publish.

Code:

function SubgridLookup(selectedEntityTypeName, selectedControl, firstPrimaryItemId, primarycontrol) {
    debugger;
    var formContext = primarycontrol,
        formId = formContext.ui.formSelector.getCurrentItem().getId();
    if (selectedControl.getRelationship().name === "new_knowlwdgearticle_knowledgearticle") {
        if (formId && formId === "f7502aaf-4874-49fc-868d-cc201c677678") {
            var viewGuid = "E2991C12-25D7-4BF0-A4DA-DC561A94678";
        }
        else if (formId && formId === "g3682787d-4874-49fc-868d-cc201c677678") {
            var viewGuid = "E2991C12-78YR-4BF0-A4DA-DC561A94678";
        }

        var options = {
            allowMultiSelect: true,
            defaultEntityType: "knowledgearticle",
            entityTypes: ["Knowledgearticle"],
            defaultViewId: viewGuid

        };

        lookupAddExistingRecords("new_knowlwdgearticle_knowledgearticle", "knowledgearticle", "knowledgearticle", firstPrimaryItemId, selectedControl, options, primarycontrol);
    }
    else {
        // Any other contact relationship (N:N or 1:N) - use default behaviour
        XrmCore.Commands.AddFromSubGrid.addExistingFromSubGridAssociated(selectedEntityTypeName, selectedControl);
    }
}

        

function lookupAddExistingRecords(relationshipName, primaryEntity, relatedEntity, parentRecordId, gridControl, lookupOptions, primarycontrol) {
    debugger;
    Xrm.Utility.lookupObjects(lookupOptions).then(function (results) {
        // Get the entitySet name for the primary entity
        Xrm.Utility.getEntityMetadata(primaryEntity).then(function (primaryEntityData) {
            var primaryEntitySetName = primaryEntityData.EntitySetName;

            // Get the entitySet name for the related entity
            Xrm.Utility.getEntityMetadata(relatedEntity).then(function (relatedEntityData) {
                var relatedEntitySetName = relatedEntityData.EntitySetName;

                // Call the associate web api for each result (recursive)
                associateAddExistingResults(relationshipName, primarycontrol, primaryEntitySetName, relatedEntitySetName, relatedEntity, parentRecordId.replace("{", "").replace("}", ""), gridControl, results, 0)
            });
        });
    });
}
function associateAddExistingResults(relationshipName, primarycontrol, primaryEntitySetName, relatedEntitySetName, relatedEntity, parentRecordId, gridControl, results, index) {
    debugger;
    var formContext = primarycontrol;
    if (index >= results.length) {
        // Refresh the grid once completed
        if (gridControl) { gridControl.refresh(); }
        return;
    }
    var lookupId = results[index].id.replace("{", "").replace("}", "");
    var lookupEntity = results[index].entityType || results[index].typename;

    var primaryId = parentRecordId;
    var relatedId = lookupId;
    if (lookupEntity.toLowerCase() !== relatedEntity.toLowerCase()) {
        // If the related entity is different to the lookup entity flip the primary and related id's
        primaryId = lookupId;
        relatedId = parentRecordId;
    }

    var association = { '@odata.id': formContext.context.getClientUrl() + "/api/data/v9.0/" + relatedEntitySetName + "(" + relatedId + ")" };

    var req = new XMLHttpRequest();
    req.open("POST", formContext.context.getClientUrl() + "/api/data/v9.0/" + primaryEntitySetName + "(" + primaryId + ")/" + relationshipName + "/$ref", true);
    req.setRequestHeader("Accept", "application/json");
    req.setRequestHeader("Content-Type", "application/json; charset=utf-8");
    req.setRequestHeader("OData-MaxVersion", "4.0");
    req.setRequestHeader("OData-Version", "4.0");
    req.onreadystatechange = function () {
        if (this.readyState === 4) {
            req.onreadystatechange = null;
            index++;
            if (this.status === 204 || this.status === 1223) {
                // Success
                // Process the next item in the list
                associateAddExistingResults(relationshipName, primarycontrol, primaryEntitySetName, relatedEntitySetName, relatedEntity, parentRecordId, gridControl, results, index);
            }
            else {
                // Error
                var error = JSON.parse(this.response).error.message;
                if (error === "A record with matching key values already exists.") {
                    // Process the next item in the list
                    associateAddExistingResults(relationshipName, primarycontrol, primaryEntitySetName, relatedEntitySetName, relatedEntity, parentRecordId, gridControl, results, index);
                }
                else {
                    Xrm.Navigation.openAlertDialog(error);
                    if (gridControl) { gridControl.refresh(); }
                }
            }
        }
    };
    req.send(JSON.stringify(association));
}

4.Need to customize the ribbon button (using the ribbon workbench). If you’re filtering a N:N, you need to customize the command for the N:N button (called AddExistingAssoc) on the SubGrid ribbon for your related entity.

5.Need to the added the parameter your are using like “SelectedEntityTypeName,SelectedControl,FirstPrimaryItemId,PrimaryControl”.

5.Publish the RibbonWorkbench.

Now you will see the records based on the view.

 

Advertisement

4 thoughts on “Dynamics 365 – Sub grid Add Existing Look up View N:N

  1. Hi Bipin, I have a similar requirement, on Marketing list for adding members subgrid, i need to apply custom view. but could you please help me with below queries

    Where to register this code is it on form load ?
    What are there id’s
    if (formId && formId === “f7502aaf-4874-49fc-868d-cc201c677678”) {
    var viewGuid = “E2991C12-25D7-4BF0-A4DA-DC561A94678”;
    }
    else if (formId && formId === “g3682787d-4874-49fc-868d-cc201c677678”) {
    var viewGuid = “E2991C12-78YR-4BF0-A4DA-DC561A94678”;
    }

    Like

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s