Format Name using Javascript in CRM 2011

2 Aug
2012

First we need to create a simple web resource either in the system customization or in a separate solution. So click on web resources and click new. Name the web resource appropriately and then select ‘Script (Jscript)’ from the type drop down. Now you can add/edit the script in three ways.

  1. Use the edit button and type your code straight into the dialog. Ok but there is no formatting, no intellisence, so not great.
  2. Use a decent editor outside of CRM and then just cut and paste into the editor.
  3. Use  a decent editor and save the file and then upload it using the browse button on the dialog.

The choice is yours!!!

Any way below is some script which takes employees details and builds their full name.


function BuildFullName() {

   //Title is a drop down so we use the getText method
   var vTitleText =  Xrm.Page.getAttribute("new_title").getText();
   var vFirstName = Xrm.Page.getAttribute("new_firstname").getValue();
   var vLastName = Xrm.Page.getAttribute("new_lastname").getValue();
   var vFullName = '';

   if (vTitleText != null) { vFullName =  vTitleText ; }

   if (vFirstName != null)    {
     if (vFullName != '') { vFullName = vFullName + ' ' + vFirstName; }
     else { vFullName = vFirstName; }    }

   if (vLastName != null)    {
      if (vFullName != '') { vFullName = vFullName + ' ' + vLastName; }
      else { vFullName = vLastName; }
   }

   if (vFullName != null) { Xrm.Page.getAttribute("new_fullname").setValue(vFullName); }
}

Now we need to add the web resource to the employee form. Open the form and click form properties.
 FormatName_JS_CRM2011_3

Now add your web resource to the form libraries.

FormatName_JS_CRM2011_2

We now need to add the JS function to each of our fields that will build the employee name. So if you double click on the field a dialog will appear. Click on the events tab. Make sure the event dropdown is set to OnChange then click add. Select your web resource from the Library dropdown and then enter your function name into the function field (as show below).

FormatName_JS_CRM2011_3

Now click OK and then save the form. Then make sure you publish all the customizations.
Hope this simple blog helps someone.

Any questions or feedback is always welcome.

Leave a Reply