Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set the internal name for a SPField in SharePoint 2010?

I add fields to a list programmaticly. The following line adds a new field´to an existing List

Lists.AddFieldToList(warrantyList, SPFieldType.Text, "internalFieldName", "ShownFieldName", "Comment", false, false, false);                    

This is the method that is called:

public static bool AddFieldToList(SPList list, SPFieldType fieldType, string fieldInternalName, string fieldDisplayName, string fieldDescription, bool unique, bool required, bool indexed)
    {
        SPField field = new SPField(list.ParentWeb.Fields, fieldType.ToString(), fieldInternalName);             
        bool success = AddFieldToList(list, field, fieldDisplayName, fieldDescription, unique, required, indexed);
        return success;
    }

after the first line of the method the field is filled with a lot of information, but no internalName(NULL) and a Title that contains "internalFieldName".

In the second line the following method is called:

  public static bool AddFieldToList(SPList list, SPField field, string fieldDisplayName, string fieldDescription, bool unique, bool required, bool indexed)
    {
        if (field != null &&
            (!list.Fields.Contains(field.Id)))
        {

            field.ReadOnlyField = false;
            field.Title = fieldDisplayName;
            field.Description = fieldDescription;
            field.EnforceUniqueValues = unique;
            field.Indexed = indexed;
            field.Required = required;
            list.Fields.Add(field);
            return true;
        }

        return false;
    }

After that the title is changed to "ShownFieldName" (of course). But my goal is to have an internalname "internalFieldName" which has a Displayname "ShownFieldName", so "ShownFieldName" is shown in the List but I can access the item by the internal name

as field.InternalName is readOnly: How can I solve that issue?

like image 996
Ole Albers Avatar asked Nov 08 '11 15:11

Ole Albers


1 Answers

This line creates an SPField object that could have the internal name you need (displayName passed to the constructor equals fieldInternalName):

SPField field = new SPField(list.ParentWeb.Fields, fieldType.ToString(), fieldInternalName);

but before anything has been saved to the database you change it in this line:

field.Title = fieldDisplayName;

Here's the solution:

  1. Add a field to the list passing internalFieldName as both fieldInternalName and fieldDisplayName.
  2. Call the SPList.Update() method.
  3. Get the field reference from the list and change its Title property to ShownFieldName.
  4. Call the SPField.Update() method.
like image 71
Marek Grzenkowicz Avatar answered Sep 20 '22 16:09

Marek Grzenkowicz