CRM 2011 Auto-populate Name from Fields or Attributes

Are you tired of thinking about what to put into the name field when creating records and want a way to populate that name automatically?

I have created a service extension method to make my life easier. The goal of this is to autopopulate name field using the format like [field1] - [field2] - [field3] through pre-plugin:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Query;
using Microsoft.Xrm.Sdk.Messages;
using Microsoft.Xrm.Sdk.Metadata;
using System.ServiceModel;
 
namespace My.Plugins
{
    public static class ServiceExtensions
    {
        public static string GenerateNameByFields(this IOrganizationService service, Entity entity, ColumnSet colSet, string message)
        {
            var list = new List<string>();
 
            foreach (string fieldName in colSet.Columns)
            {
                //fields changed
                if (entity.Contains(fieldName))
                {
                    if (entity[fieldName] != null)
                    {
                        //check if lookup field
                        if (entity.Attributes[fieldName].GetType().Equals(typeof(Microsoft.Xrm.Sdk.EntityReference)))
                        {
                            string primaryNameAttribute = service.GetPrimaryNameAttributeByLookupField(entity, fieldName);
 
                            //needs to use retrieve to get the lookup entity first
                            string lookupEntityName = ((EntityReference)entity.Attributes[fieldName]).LogicalName;
                            Entity lookupEntity = service.Retrieve(lookupEntityName, ((EntityReference)entity[fieldName]).Id, new ColumnSet(true));
                            if (lookupEntity.Attributes.Contains(primaryNameAttribute))
                            {
                                list.Add(lookupEntity.Attributes[primaryNameAttribute].ToString());
                            }
                        }
                        //for boolean other than yes/no
                        else if (fieldName == "new_type")
                        {
                            string type = ((bool?)entity.Attributes[fieldName]).Value == false ? "Win" : "Loss";
                            list.Add(type);
                        }
                        else
                        {
                            list.Add(entity.Attributes[fieldName].ToString());
                        }
                    }
                }
 
                //fields unchanged - use retrievedEntity
                else
                {
                    if (message == "update")
                    {
                        Entity retrievedEntity = service.Retrieve(entity.LogicalName, entity.Id, colSet);
 
                        if (retrievedEntity != null && retrievedEntity.Contains(fieldName))
                        {
                            //check if lookup field
                            if (retrievedEntity.Attributes[fieldName].GetType().Equals(typeof(Microsoft.Xrm.Sdk.EntityReference)))
                            {
                                list.Add(((EntityReference)retrievedEntity.Attributes[fieldName]).Name);
                            }
                            else if (fieldName == "new_type")
                            {
                                string type = ((bool?)retrievedEntity.Attributes[fieldName]).Value == false ? "Win" : "Loss";
                                list.Add(type);
                            }
                            else
                            {
                                //check if it's a decimal value
                                decimal decimalNumber = 0;
                                bool canConvert = decimal.TryParse(retrievedEntity.Attributes[fieldName].ToString(), out decimalNumber);
                                if (canConvert == true)
                                    list.Add(String.Format("{0:0.##}", decimalNumber));
                                else
                                    list.Add(retrievedEntity.Attributes[fieldName].ToString());
                            }
                        }
                    }
                }
            }
 
            //join the string with the delimiter
            string generatedName = string.Join(" - ", list);
            return generatedName;
        }
 
        public static string GetPrimaryNameAttributeByLookupField(this IOrganizationService service, Entity entity, string fieldName)
        {
            RetrieveEntityRequest retrieveRequest = new RetrieveEntityRequest
            {
                EntityFilters = EntityFilters.Entity,
                LogicalName = ((EntityReference)entity[fieldName]).LogicalName
            };
            RetrieveEntityResponse retrieveResponse = (RetrieveEntityResponse)service.Execute(retrieveRequest);
 
            return retrieveResponse.EntityMetadata.PrimaryNameAttribute;
        }
    }
}


To use this you just need to construct the column set and pass in the entity from the plugin context:

1
2
3
4
5
//Generate Name
ColumnSet colSet = new ColumnSet("new_field1", "new_field2", "new_field3");
string generatedName = service.GenerateNameByFields(entity, colSet);
 
entity["new_name"] = generatedName;      


We also need a javascript to disable this name field when the form load:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
// JScript source code
function Form_onload() {
    setAutoName("new_name");
}
 
function setAutoName(fieldname) {
    var nameField = Xrm.Page.getAttribute(fieldname).getValue();
 
    if (nameField != null) {
        SetDisableField(fieldname, true);
    }
    else {
        Xrm.Page.getAttribute(fieldname).setValue("<System Generated>");
        SetDisableField(fieldname, true);
    }
}


Hope this helps,
Andreas

Comments

Popular posts from this blog

SharePoint 2013 anonymous access add attachments to list item

CRM Plugin - Parent and Child Pipeline