Creating Naming Plugins in Dynamics CRM 2011

Roshan Mehta, 29 March 2012

In this post, we will take a look at how we can write a plugin to set the primary field for an entity. This is important because lookup views MUST have the primary field as the first column. Unfortunately for system customizers, this field cannot be removed from the view.

For example, I have created a custom entity called “Inquiry”. By default, entities have a primary field called “Name”. Let’s assume that whenever a customer calls our company, we want to fill out the details of their inquiry in our custom entity. We don’t want to enter details into the “Name” field each time, so we can let a plugin automatically generate the name for us based on the “First Name”, “Last Name” and the “Created On” date.

Firstly, let’s see what the issue is if we have a lookup from a Contact to the Inquiry entity without the “Name” field being set.

 Creating Naming Plugins in CRM 2011

Notice that there is no meaningful data in this view and it is near impossible to find a specific record. As mentioned earlier, the “Name” field cannot be removed from the Inquiry Lookup View. We need to use a plugin to prefill the “Name” field based on other information on the form. I have created a plugin to run on pre-create of the Inquiry entity. The code snippet to set the name is as follows:

        private void SetName(Entity target)
        {
            string firstName = target.GetAttributeValue<string>("mag_firstname");
            string lastName = target.GetAttributeValue<string>("mag_lastname");
            DateTime createdOn = target.GetAttributeValue<DateTime>("createdon"); 

            string name = string.Format("{0} {1} - {2}", firstName, lastName, createdOn);
            target["mag_name"] = name;
        }

Now we can see the plugin in action. When we create a new Inquiry and click on save, the “Name” field is automatically prefilled. Now the Inquiry lookup view has some meaningful data to distinguish between different records.

 Creating Naming Plugins in CRM 2011

Naming plugins can be used for any entity and we can extend the complexity by pulling through values from related entities.