Populate Data From Child Record To Parent Record’s Quick Create Form In Dynamics 365

Populating data on forms in CRM is not a headache since you can do mappings for your 1:N record or simply do a Web API request using the parent lookup exist on the new form to retrieve the values from that record and set them on the current form.

However what if you have to populate data on a parent record form from a child record form? there is no out of the box functionality or script available for this. I digged in further and found below method. Its a rare but an important requirement. 

  1. I have an entity named “Potential Customer” which has a lookup of Contact along with some other fields such as name, contact ref number etc. My requirement is to pass name and contact ref from potential customer to contact on quick create form:
  2. Here are the two field below the parent contact lookup which I would like to be propagated to contact quick create form:
  3. To achieve this, I have used a concept of localStorage property.
  4. Create below javascript resource and add to your child record form( from where you will add new parent record) in my case its potential customer:
function SetLocalStorage(executionContext)
{

var formContext = executionContext.getFormContext();
var firstName = formContext.getControl("new_name").getAttribute().getValue().toString();
var refNumber = formContext.getControl("new_contactrefnumber").getAttribute().getValue();

localStorage.setItem("FirstName",firstName );
localStorage.setItem("ContactRef",refNumber );

}

In the code above I am simply retrieving the value from current record on load event and setting it to the localStorage. You have to set value using a key and the value. so from code below; FirstName is the key(using which we will retrieve the value) and firstName variable is the value.

localStorage.setItem(“FirstName”,firstName );

       
         5. Now add below code to your onload quick create form of the parent record in my case its contact.         

function RetrieveStorageValue(executionContext)
{
debugger;
var formContext = executionContext.getFormContext();
var firstName = localStorage.getItem("FirstName");
var contactRef = localStorage.getItem("ContactRef");

formContext.getAttribute("firstname").setValue(firstName);
formContext.getAttribute("new_contactref").setValue(contactRef);

localStorage.removeItem("FirstName");
localStorage.removeItem("ContactRef");

}

In the above code i am simply retrieving the value set using localStorage.getItem(“KeyName”); and then setting it on the required fields.

Use this link explained very well by Neil on how to add javascript code to your form : JS Basics

So now when Click on the new button from the lookup dropdown to add a parent record , I get values populated:

 

Here you go! 

Few important points:  

  1. I don’t encourage using properties and methods which are not defined by/for Microsoft dynamics CRM.
  2. The data you add to localStorage doesn’t have expiration which means the data will be there unless you don’t clear it (hence in my code I clear it everything once I have  used the values)
  3. It is just one of the methods (sometimes referred to as “Unsupported”) to achieve this requirement.
  4. The above script is for Dynamics crm 365 v9 or above. Please use Xrm.Page instead of formContext if you wish to implement this in earlier versions.

 

I hope this helps! 

Advertisement

Get User’s Teams Using WebApi JavaScript In Dynamics 365

If you need to get current/logged in or of any other user’s all teams. You have to look for the N:N relationship schema name and use that association in WebApi request:

1

So below is the code you can use to achieve this requirement. I have just retrieving the name of the teams associated and putting an alert on Onload of a form.

I have generated the code using Rest Builder Tool . And added the filter ($filter=systemuserid eq  IdOfTheuser) manually.

function GetUserTeams()
{
    var userSettings = Xrm.Utility.getGlobalContext().userSettings; // userSettings is an object with user information.
    var current_User_Id = userSettings.userId; // The user's unique id
    var newid = current_User_Id.slice(1, -1);	
    var req = new XMLHttpRequest();
req.open("GET", Xrm.Page.context.getClientUrl() + "/api/data/v9.1/teams?$select=name&$expand=teammembership_association($filter=systemuserid eq "+newid+")", true);
req.setRequestHeader("OData-MaxVersion", "4.0");
req.setRequestHeader("OData-Version", "4.0");
req.setRequestHeader("Accept", "application/json");
req.setRequestHeader("Content-Type", "application/json; charset=utf-8");
req.setRequestHeader("Prefer", "odata.include-annotations=\"*\"");
req.onreadystatechange = function() {
    if (this.readyState === 4) {
        req.onreadystatechange = null;
        if (this.status === 200) {
            var results = JSON.parse(this.response);
            for (var i = 0; i < results.value.length; i++) {
                var name = results.value[i]["name"];
                             
                alert(name);
            }
        } else {
            Xrm.Utility.alertDialog(this.statusText);
        }
    }
};
req.send();
}

I am calling the function on Onload event of lead record. My user has two teams associated to it:

1


2


Important – Make sure you format the code fully before you use it. i.e use the latest method in the script i.e not using Xrm.Page but rather the formContext for v9.

I hope this helps! Cheers!

 

Get Selected Record Information From Main View Or A Subgrid In Dynamics 365

I recently had a requirement to get selected record id from a main view of an entity i.e. Home page view of an entity and also on a subgrid within the form.

I also needed to pass this ID to my action to do some further operations in the plugin. This is how I did

I have taken reference from  here  and here.

  1. Download the managed solution of Ribbon Workbench from here and import it to your Dynamics CRM 365 environment: https://www.develop1.net/public/rwb/ribbonworkbench.aspx
  2. Create an unmanaged  solution and add contact entity to it. ( I am taking contact entity as I need to perform action on that, you can select any entity)
  3. Create two JPG images web resource with sizes as 16×16 and 32×32 for your ribbon button. You can take the desired image and rescale it online.
  4. Create a javascript web resource and below code to it:
    function GetRecordInformation(item)
    {
        var selectedItem = item[0];
       alert("You have Select Record with Id=" + selectedItem.Id + "\nName=" 
    	+ selectedItem.Name + "\nEntity Type Code=" + selectedItem.TypeCode.toString() + "\nEntity=" + selectedItem.TypeName);
    }
  5. Publish all your customization and open ribbon workbench tool from your solution area and select the solution that you have created and click ok:1.png
  6. Now drag and drop a button to the home grid view:1.png
  7. I have named this button as “SELECT” from the button properties you will get once you add and select the button on bottom right side of the ribbon workbench also select the Image for you button by providing the web resources we created in step 3 :1
  8. Now that out button is ready, we need to add a command and enable rule to it. to do this from the solution component area click on commands and click on + button and then from the right side click on add “Action”  and then click on “Javascript action”:1.png
  9. Add your javascript resource by searching in the lookup, if you dont find the script( i faced the issue). Simply add $webresource:WebResourceName for me its $webresource:new_SelectRecord  
  10. In the next box – add the function name i.e for me its GetRecordInformation
  11. Then click on Add parameter and select SelectedControlSelectedItemReferences Parameter. It should look like below:

    1

  12. The final step is to add an enable rule to this command. To do this – from the solution component area click on Enable Rules and click on + button. On your right side you will be presented with below, Make sure you keep the information as it is:1
  13. We are done , now click on Publish from the ribbon. wait for it to completed as it might take some time. Once done navigate to your dynamics CRM and the main entity home view, you should see the button:1.png
  14. Select a record and click on the button and Bammmm! if everything goes right you will get the record information.1

You can do the same thing on a form subgrid, all you have to do is place the button on a form grid instead of home view.

I needed to further processing with the data so I called an action and passed the record id described here : http://sacconsulting.blogspot.com/2017/03/how-to-call-global-action-from.html

I hope this has been helpful!

Make All fields Mandatory/Optional On Form Using Javascript

This should be a very quick blog on JavaScript helper which will let you make all fields on the form mandatory or optional. This requirement is hypothetical; I have not received any till now.

I am going to be calling below function on OnLoad event of the form based on a field value but you can very well call is on OnSave of record, or OnChange event of field.

For Dynamics CRM below v9:

function SetRequiredLevel()    
{
  var attributes = Xrm.Page.data.entity.attributes.get();
    for (var i in attributes) {
        attributes[i].setRequiredLevel("required");
    }
}

For Dynamics CRM v9 or above use below and make sure pass the context as first parameter ( checkbox) on the form editor while calling the function.

function SetRequiredLevel(executionContext)    
{
  var context = executionContext.getFormContext();
  var attributes =  context.data.entity.attributes.get();
    for (var i in attributes) {
        attributes[i].setRequiredLevel("required");
    }
}

1

 

1. If you need to check some value you can do that i.e.

If ( fieldAValue = 1)

{
//the above code goes here//

}

2. If you have to make fields optional rather then mandatory , do this:
setRequiredLevel(“none“);

I hope this helps!!

Get Api Version Dynamically For WebApi Requests

In this post I will quickly cover the requirement of dynamically getting API version of dynamics CRM in JavaScript rather then hard coding it , so that in next releases your JavaScript doesn’t break. I am referring to this:

1

For Dynamics CRM version 8.2 or below, do this:

var apiVersion = Xrm.Page.context.getVersion();

For Dynamics CRM version 9 or above, do this:

var apiVersion = Xrm.Utility.getGlobalContext().getVersion();

2

It will give you an expanded version which includes minor and major versions. Now, all you have to do is crop the number to get only initial numbers such as 9.1 in this case:

var shortVersion= apiVersion.substring(3, myStr.indexOf(“.”) -1);

then finally use it in your request as:

    req.open("GET",Xrm.Utility.getGlobalContext().getClientUrl()+ "/api/data/"+shortVersion+"/systemusers

Hope this helps!

Count Total Subgrid Records in Dynamics CRM using JavaScript

In one of my previous blog I explained,how a rollup field can be used to count child records : Count the number of related child records using a Rollup field

However, Rollup field is calculated with an Async System Job, therefore, if you need something to be triggered on every form load; you will have to write a JS.

Here is a quick code to count the number of related sub-grid record on a form onload. You can put an alert of the count or add that number to a field.

function getTotalGridRecordCount() {
 debugger;
 try {

setTimeout(function () {
 if (Xrm.Page != null && Xrm.Page != undefined && Xrm.Page.getControl("contactopportunitiesgrid") != null && Xrm.Page.getControl("contactopportunitiesgrid") != undefined) {
 var count = Xrm.Page.getControl("contactopportunitiesgrid").getGrid().getTotalRecordCount();
 alert("Total Opportunities:"+count);

}
 }, 5000);
 }
 catch (e) {
 Xrm.Utility.alertDialog(functionName + "Error: " + e.message || e.description);
 }
}

Add script to the form and call this function on Onload event. Open the form to see it in action:

1

 

Hope this helps! cheers!

How to set PartyList in Microsoft Dynamics CRM using Javascript

Let make it a smallest blog possible.

below code i have been using without any issue when it comes to setting a partylist or multi lookup in CRM. In the below code i am retrieving the contact id or the id of entity which is there in the regarding field & setting it on the “From” field.

function setCallFrom() 
{
 var lookup = new Array();
 lookup = Xrm.Page.getAttribute("regardingobjectid").getValue();
 if (lookup != null) {
 var name = lookup[0].name;
 var id = lookup[0].id;
 var entityType = lookup[0].entityType;
 if (entityType == "contact") {

var value = new Array();
 value[0] = new Object();
 value[0].id = id;
 value[0].name = name;
 value[0].entityType = "contact";

Xrm.Page.getAttribute("from").setValue(value);
 }

}
}

With slight modifications you can use the code on any other activity if you need to set partylist.

Call this function on Onload of the record or on onchange of the regarding field.

hope this helps!

Cheers!

Lock all fields on a form using Javascript- Microsoft Dynamics CRM

Hi Guys,

We all get requirements to lock the whole form to stop people from editing the record.

There are some out of the box options available to achieve this :

  1. Create a business rule : you can easily create a business and use lock field feature however you will have to select all the field on the form one by one – for .e.g if you have 50 fields on the form, you will have to add action for all of them. Moreover another limitation is if a field is removed from the form – you business rule will stop working.
  2. We all know if record is status is set to inactive – form become uneditable but in this scenarios we want to keep the record but uneditable.

Therefore, we come down to our final easy solution to tackle all problems above, the Javascript. Have a look on the below code :

 function disableFormFields()

{

       Xrm.Page.ui.controls.forEach(function (control, index) {

           var controlType = control.getControlType();

           if (controlType != “iframe” && controlType != “webresource” && controlType != “subgrid”)

           {

               control.setDisabled(true);

           }

       });

}

above code takes the control of the form directly rather then of each field & locks all of them. Just call the function on Onload , I have used this on my form and it looks like below:

lockfield

 

Now you can definitely add your own logic into this code for .e.g you put a if condition to check some value based on which you want to lock all fields and another things if you need to leave some fields unlocked you can again you a if condition , check the value and use below

just add the below code to above code :

if (crmfield = abc)

{

Xrm.Page.ui.controls.get(“CrmFieldShcemaname1”).setDisabled(false);

Xrm.Page.ui.controls.get(“CrmFieldShcemaNam2”).setDisabled(false);

Xrm.Page.ui.controls.get(“CrmFieldShcemaNam2”).setDisabled(false);

}

 

hope this helps you!

cheers