SharePoint Blogs / SharePoint University
SharePoint Blogs and SharePoint University - all in one place!
Need SharePoint Training? Attend a SharePoint Bootcamp!

Please delete cookies related to sharepointblogs.com and sharepointu.com to resolve login issues!

Create custom field types for SharePoint

In this example we are creating a custom field type which concatenates two text fields (first and last name).

  1. Create a new usercontrol file (customfieldcontrol.ascx). In this usercontrol, add a SharePoint:RenderingTemplate control, and insert whatever you want for your control template.

  2. <%@ Control Language="C#" %>

    <%@ Assembly Name="CustomControls, Version=1.0.0.0, Culture=neutral, PublicKeyToken=xxxxxxxxxxxxxxxx" %>

    <%@ Register TagPrefix="SharePoint" Assembly="Microsoft.SharePoint, Version=12.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" Namespace="Microsoft.SharePoint.WebControls" %>

     

    <SharePoint:RenderingTemplate Id="CustomFieldRendering" runat="server">

        <Template>

            <asp:TextBox runat="server" ID="txtFirstName" /> <asp:TextBox runat="server" ID="txtLastName" />

        </Template>

    </SharePoint:RenderingTemplate>


  3. Secondly, create a new class file (customfieldcontrol.cs), which will take the role of codebehind file of the usercontrol. In this class, which will inherit from Microsoft.SharePoint.WebControls.BaseFieldControl, we will override some of the properties and methods to implement our own logic.

  4. using System;

    using System.Collections.Generic;

    using System.Text;

    using System.Web.UI.WebControls;

     

    using Microsoft.SharePoint;

    using Microsoft.SharePoint.WebControls;

     

    namespace CustomControl

    {

        public class customfieldcontrol : BaseFieldControl

        {

            protected TextBox txtFirstName;

            protected TextBox txtLastName;

     

            protected override string DefaultTemplateName

            {

                get { return "CustomFieldRendering"; }

            }

            public override object Value

            {

                get

                {

                    EnsureChildControls();

                    return txtFirstName.Text + "%" + txtLastName.Text;

                }

                set

                {

                    try

                    {

                        EnsureChildControls();

                        txtFirstName.Text = value.ToString().Split('%')[0];

                        txtLastName.Text = value.ToString().Split('%')[1];

                    }

                    catch { }

                }

            }

            public override void Focus()

            {

                EnsureChildControls();

                txtFirstName.Focus();

            }

            protected override void CreateChildControls()

            {

                if (Field == null) return;

                base.CreateChildControls();

     

                //Don't render the textbox if we are  just displaying the field

                if (ControlMode == Microsoft.SharePoint.WebControls.SPControlMode.Display) return;

     

                txtFirstName = (TextBox)TemplateContainer.FindControl("txtFirstName");

                txtLastName = (TextBox)TemplateContainer.FindControl("txtLastName");

                if (txtFirstName == null) throw new NullReferenceException("txtFirstName is null");

                if (txtLastName == null) throw new NullReferenceException("txtLastName is null");

                if (ControlMode == Microsoft.SharePoint.WebControls.SPControlMode.New)

                {

                    txtFirstName.Text = "";

                    txtLastName.Text = "";

                }

            }

        }

    }


    Actually, what this code does is:

    Define the ID of the renderingtemplate control in our usercontrol.
    Set the return value to the value we want it to return :), in this case this will be something like Firstname%Lastname.
    Make sure that when you edit an item, the proper values are filled in into the textboxes again.

  5. Next thing to do is to create the Field type class (CustomField.cs) itself. In this class, which derives of one of the base control types from SharePoint (SPFieldText, SPFieldChoice, ...), we will define which control has to be used as template, and which value has to be returned when displaying a list item.

    using Microsoft.SharePoint;

    using Microsoft.SharePoint.WebControls;

     

    namespace CustomControl

    {

        public class CustomField : SPFieldText

        {

            public CustomField(SPFieldCollection fields, string fieldName)

                : base(fields, fieldName)

            { }

     

            public CustomField(SPFieldCollection fields, string typeName, string displayName)

                : base(fields, typeName, displayName)

            { }

     

            public override BaseFieldControl FieldRenderingControl

            {

                get

                {

                    BaseFieldControl fieldControl = new customfieldcontrol();

                    fieldControl.FieldName = this.InternalName;

                    return fieldControl;

                }

            }

     

            public override string GetValidatedString(object value)

            {

                return value.ToString().Split('%')[1].ToUpper() + " " + value.ToString().Split('%')[0];

            }

        }

    }


    Main thing of this code is the GetValidatedString() function. This function defines what is to be displayed when you display an item (in a list view for example).
    In our case, which in our case will be something like LASTNAME Firstname.

  6. Last file to create is the XML File (fldtypes_custom.xml), which will add the custom field type to SharePoint.

    <?xml version="1.0" encoding="utf-8"?>

    <FieldTypes>

      <FieldType>

        <Field Name="TypeName">CustomField</Field>

        <Field Name="ParentType">Text</Field>

        <Field Name="TypeDisplayName">Custom Name Field</Field>

        <Field Name="TypeShortDescription">Custom Name Text Field</Field>

        <Field Name="UserCreatable">TRUE</Field>

        <Field Name="ShowOnListCreate">TRUE</Field>

        <Field Name="ShowOnSurveyCreate">TRUE</Field>

        <Field Name="ShowOnDocumentLibrary">TRUE</Field>

        <Field Name="ShowOnColumnTemplateCreate">TRUE</Field>

        <Field Name="Sortable">TRUE</Field>

        <Field Name="Filterable">TRUE</Field>

        <Field Name="FieldTypeClass">CustomControl.CustomField, CustomControl, Version=1.0.0.0, Culture=neutral, PublicKeyToken=xxxxxxxxxxxxxxxx</Field>

        <Field Name="SQLType">nvarchar</Field>

      </FieldType>

    </FieldTypes>


  7. So far so good with creating the files :) Now, all we have to do is put the right files in the right places ...
    Compile your project (or at least both .cs classes) and make sure they are strong named.
    Then, install them in the GAC (%windir%\assembly)

    Next, copy the .ascx file to C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\12\TEMPLATE\CONTROLTEMPLATES

    And the last file to copy: copy the .xml file to C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\12\TEMPLATE\XML
  8. That's it. Maybe do an IISRESET, and you can use your newly created Custom Field Type!

Edit: changed the ShowIn* to ShowOn* (thanks Phil for noticing!)

Posted 08-31-2007 12:35 PM by nsevens

Comments

Integrating Radi with Sharepoint and Dynamics CRM wrote WSS Custom Field Type linked to Microsoft CRM entities (Part 1)
on 09-01-2007 8:10 PM

Here is how I created custom columns within Document Libraries and Lists which display data from Dynamics

SharePoint 2007 link love 09-03-2007 part deux at Virtual Generations wrote SharePoint 2007 link love 09-03-2007 part deux at Virtual Generations
on 09-03-2007 6:46 AM

Pingback from  SharePoint 2007 link love 09-03-2007 part deux at  Virtual Generations

11 Links Today (2007-09-05) wrote 11 Links Today (2007-09-05)
on 09-05-2007 10:19 AM

Pingback from  11 Links Today (2007-09-05)

Arun wrote re: Create custom field types for SharePoint
on 09-12-2007 2:34 AM

Hello Nick,

Tnaks for the great article. But I've some more doubts.

I am creating a custom field type for sharepoint list.

I created the custom field by inheriting the sharepoint base field SPFieldMultiLineText.  I‘ve also created a custom field property

“SearchPath” as follows…

private string _searchPath

       public string SearchPath

       {

           get

           {

               return _ searchPath;

           }                                                                        

           set

           {

               this._ searchPath = value;

           }

       }

for rendering custom property I have created an .ascx file along with a code-behind inherited from User Control and  IFieldEditor.

I could able to access and modify the custom property from within the  methods InitializeWithField()  and OnSaveChange().

I have created another .ascx file and a code-behind file as Field rendering Usercontrol inherited from BaseFieldControl for providing UI for data entry into the listt. I want to implement some logic during this data entry based on the custom field’s additional property value.

But my problem is I could not access the custom property of my custom field class from within the Field Rendering User control.

How I can access the custom field’s custom property values within the field rendering usercontrol?

Please help me.

Arun

nsevens wrote re: Create custom field types for SharePoint
on 09-12-2007 4:04 AM

Hi Arun,

I haven't tried that out myself actually. I'll try to figure it out in the next couple of days.

If I've got something, I'll let you know.

DanB wrote re: Create custom field types for SharePoint
on 09-13-2007 6:45 AM

Hi Nick,

Did you try to edit in datsheet? In my list, the custom fields appear red-only in datasheet. Do you know how to fix this?

Thanks,

Dan

nsevens wrote re: Create custom field types for SharePoint
on 09-13-2007 8:25 AM

Dan,

I have not been able to correct that yet. It appears that all custom fields tend to show up read only in datasheet view. Even if you don't add any logic at all (just a simple renamed text field)

nsevens wrote re: Create custom field types for SharePoint
on 09-18-2007 6:51 AM

Arun,

I might have found the solution to your problem ...

Check out this post:

207.46.236.188/.../ShowPost.aspx

might help ;)

Priya wrote re: Create custom field types for SharePoint
on 01-28-2008 6:29 AM

I have successfully implemented your custom field type.

now i have a problem.

i need to get the clientid of the textbox in my.ascx.

it is always returning null.

please send me a solution for this

Armando wrote re: Create custom field types for SharePoint
on 02-18-2008 1:19 AM

hi

I want to create custom field that is not editable by user and get it's value base on content Type of item that will be created and some other things. my problem is when user begin create to new item(e.g from A content Type) that item actually is null until user click OK, and I can't get its type from ListItem.ContentType.Name because ListItem is null? is there any method of this class or in other class to get type of item in creation state.

nsevens wrote re: Create custom field types for SharePoint
on 02-18-2008 4:25 AM

Armando,

You should try requesting the content type id out of the New Item page's querystring.

this.Context.Request.QueryString["ContentTypeId"]

Then get the content type from that Id and I think you'll be on your way after that ;)

Nick

phil wrote re: Create custom field types for SharePoint
on 03-13-2008 3:46 PM

MSDN docs show an "On" not an "In" in the names; "ShowOnListCreate" instead of "ShowInListCreate", same for the others.

phil wrote re: Create custom field types for SharePoint
on 03-14-2008 9:59 AM

The field property names should be "ShowOn..."  not "ShowIn...".   So "ShowInListCreate" should be "ShowOnListCreate".  

See here: msdn2.microsoft.com/.../microsoft.sharepoint.spfieldtypedefinition.showonlistcreate.aspx

and here msdn2.microsoft.com/.../aa544201.aspx

Mawm wrote re: Create custom field types for SharePoint
on 03-24-2008 3:51 PM

Hi,

I am trying to use a custom field rendering control in a list view, instead of using the <RenderPattern> element in the fldtypes xml file.  MSDN docs say I should be able to assign a rendering control in display mode as well as edit and new mode.  Is display mode the same as list view?

protected override System.Web.UI.ITemplate ControlTemplate        

{            

   get          

   {                              

       if (ControlMode == Microsoft.SharePoint.WebControls.SPControlMode.Display)                

       {                    

           return SPControlTemplateManager.GetTemplateByName("DisplayVoteFieldControl");                    

          //return base.DisplayTemplate;                  

           // return base.ControlTemplate;                

       }                

      else              

      {                  

            return base.ControlTemplate;                

       }                            

   }        

}

This is how I am trying to switch rendering controls in my BaseFieldControl class.  I have noticed, though, that the ControlTemplate get accessor is not getting called at all in list view.

nsevens wrote re: Create custom field types for SharePoint
on 03-25-2008 1:48 AM

As far as I know (think), the list view renders the absolute value of the GetValidatedString() function is called and displayed.

I could be wrong though :$ so if someone has some more info, please let me know ;)

manu wrote re: Create custom field types for SharePoint
on 03-31-2008 4:18 AM

Hi,

 Is there any way to deploy/install custom filed types for only specific sharepoint site on farm and not for others. for e.g In my farm I want to install custom filed type for site A and not for sites B,C,D etc(these can top level sites or child sites of a top site.).

Thanks in Advance.

nsevens wrote re: Create custom field types for SharePoint
on 03-31-2008 6:22 AM

Manu, I've been looking into that for some time, but couldn't find a solution :/ sorry. I tried using features but the issue is that the custom field definition should apparently always be placed in the 12/Templates/XML directory ...

Phil wrote re: Create custom field types for SharePoint
on 04-03-2008 8:30 AM

Nick,

  For the customfieldcontrol class why not inherit from BaseTextField or TextField instead of BaseFieldControl?

Phil wrote re: Create custom field types for SharePoint
on 04-03-2008 9:17 AM

Nick,

 Can you show how to make a custom lookup field derived from SPFieldLookup?

  Thanks

nsevens wrote re: Create custom field types for SharePoint
on 04-03-2008 9:56 AM

Haven't tried that yet Phil.

I'll have a look at it tomorrow or something. If I get some results, I'll make sure to post 'em !

Erin wrote re: Create custom field types for SharePoint
on 04-04-2008 4:03 PM

Thanks for posting this sample. I should be able to adapt it to meet my needs. First I want to make it work as you described it, but I have run into a couple issues.

First, in the ascx assembly reference, I had to remove "s" from "CustomControls". No problem.

Second, the data appears to save and display correctly in view mode, but not in edit mode. It puts LASTNAME FirstName in the first field because it is trying to Split value, which is LASTNAME FirstName at that point rather than FirstName%LastName. I will try to figure this out myself, but if you can possibly look into it too that would be a great help, as I am new to both C# and Sharepoint development.

Thanks a lot!

nsevens wrote re: Create custom field types for SharePoint
on 04-07-2008 1:17 AM

Erin,

It's indeed an issue I've noticed a little while ago, however I haven't had the time to look into it yet. Will be doing it in the next few days though I hope.

Good look with your customization too ;)

Joseph wrote re: Create custom field types for SharePoint
on 04-24-2008 5:48 PM

i've found variations of the same solution on many sites so far. Everything dealing with custom controls has shown how to store data, and display that data using the fldtypes*.xml

let's say you want to display something from the SPAudit for each document. Is there a way of doing this?

Any help would be appreciated. Even if it's just an example on how to show the current Date would help me on my way

PrashanthSpark wrote re: Create custom field types for SharePoint
on 05-07-2008 4:53 AM

C:\Program Files\Common Files\Microsoft Shared\web server extensions\12\TEMPLATE\XML\FLDTYPES_AccountField.xml

<?xml version="1.0" encoding="utf-8"?>

<FieldTypes>

 <FieldType>

   <Field Name="TypeName">AccountField</Field>

   <Field Name="ParentType">Text</Field>

   <Field Name="TypeDisplayName">Account name</Field>

   <Field Name="TypeShortDescription">Account name</Field>

<Field Name="UserCreatable">TRUE</Field>

<Field Name="ShowOnDocumentLibrary">TRUE</Field>

<Field Name="ShowOnListCreate">FALSE</Field>

<Field Name="ShowOnSurveyCreate">FALSE</Field>

<Field Name="ShowOnColumnTemplateCreate">FALSE</Field>

<Field Name="Sortable">FALSE</Field>

<Field Name="Filterable">FALSE</Field>

<Field Name="SQLType">nvarchar</Field>

<Field Name="FieldTypeClass">

Account_Name.AccountField,

Account_Name,Version=1.0.0.0,Culture=neutral,

PublicKeyToken=49950b16a925559b

</Field>

 </FieldType>

</FieldTypes>

-------------------

using System;

using System.Collections.Generic;

using System.Text;

using System.Web;

using System.Web.UI;

using Microsoft.SharePoint;

using Microsoft.SharePoint.WebControls;

namespace Account_Name

{

   public class AccountFieldControl : TextField

   {

       protected override void CreateChildControls()

       {

           base.CreateChildControls();

           if (base.Field != null)

           {

               if (base.ControlMode.Equals(SPControlMode.New) ||

               base.ControlMode.Equals(SPControlMode.Edit))

               {

                   string currentValue = (base.ItemFieldValue == null ? string.Empty : base.ItemFieldValue.ToString());

                   if (string.IsNullOrEmpty(currentValue))

                   {

                       string parentValue = string.Empty;

                       try

                       {                          

                           SPFolder parentFolder = base.ListItem.File.ParentFolder;

                           parentValue = parentFolder.Name.ToString();                          

                       }

                       catch

                       { }

                       base.ItemFieldValue = parentValue;

                   }

               }

           }

       }

   }

}

----------------------

using System;

using System.Collections.Generic;

using System.Text;

using System.Web;

using System.Web.UI;

using Microsoft.SharePoint;

using Microsoft.SharePoint.WebControls;

namespace Account_Name

{

   public class AccountField : SPFieldText

   {

       public AccountField(SPFieldCollection fields,string fieldName): base(fields, fieldName)

       {            

       }

       public AccountField(SPFieldCollection fields, string typeName, string displayName)

           : base(fields, typeName, displayName)

       {

       }

       public override BaseFieldControl FieldRenderingControl

       {

           get

           {

               // Use our custom control when the field is rendered.

               BaseFieldControl control = new AccountFieldControl();

               control.FieldName = base.InternalName;

               //control.CssClass = "ms-hidden";

               control.DisableInputFieldLabel = true;

               return control;

           }

       }

       public override string GetValidatedString(object value)

       {

           return value.ToString();

       }  

   }

}

---------------

restart iis

--------------

go to sharepoint document library & add the new control type

Dave C wrote re: Create custom field types for SharePoint
on 05-15-2008 5:49 PM

Hello Nick (and Erin), any luck figuring out the issue Erin brought to our attention?

nsevens wrote re: Create custom field types for SharePoint
on 05-16-2008 2:51 AM

Dave, I'm sorry but I didn't have any luck with the issue... I'm sure it's some property I'm setting wrong, but I can't figure out what and how :s

Sharepoint custom field | ЖизниЛЕНТА wrote Sharepoint custom field | ЖизниЛЕНТА
on 06-04-2008 3:10 PM

Pingback from  Sharepoint custom field | ЖизниЛЕНТА

Brenty Boy wrote re: Create custom field types for SharePoint
on 06-19-2008 5:42 PM

I want to implement a combobox that will offer 1-n possible values to set in the property of my custom field when creating it, not when using it in the Sharepoint sites.

I was able to show an empty Combobox to users when creating the custom field, but I don't know how to fill it with values.

<PropertySchema>

 <Fields>

   <Field Name="Type" DisplayName="Select type" Type="Choice" />

   </Field>

 </Fields>

</PropertySchema>

How would I fill the ComboBox with "A";"B";"C", when setting the properties for my new custom field?

Thanks

sharma wrote re: Create custom field types for SharePoint
on 07-16-2008 6:18 AM

hi ,, i require a custom list to count folder size......

Paul wrote re: Create custom field types for SharePoint
on 07-18-2008 11:15 PM

I am trying to find the sharepoint dlls. I am looking under

C:\Program Files\Common Files\Microsoft Shared\web server extensions\12\ISAPI

but all I find is a bunch of xml files. Any ideas?

Anand Sebastian wrote re: Create custom field types for SharePoint
on 07-28-2008 4:42 AM

Hai Nick,

Can you elaborate your code from start to end with a screen shot.Or can you help me to generate unique id for each service request in helpdesk template site.But please do show it step by step.

with regards Anand

Custom field types for SharePoint « Grumpy Wookie wrote Custom field types for SharePoint &laquo; Grumpy Wookie
on 08-13-2008 8:10 AM

Pingback from  Custom field types for SharePoint &laquo; Grumpy Wookie

aslam wrote re: Create custom field types for SharePoint
on 08-28-2008 1:18 AM

i am not able to create a datasheet view in moss 2007

link whcih allows to create  a datasheet view is not visible

Baloucci wrote re: Create custom field types for SharePoint
on 09-03-2008 6:54 PM

How do we create custom upload field type, does any body have any idia?

Thanks

SharePoint 2007 Link List « Prashant Jadhav wrote SharePoint 2007 Link List &laquo; Prashant Jadhav
on 10-20-2008 11:34 PM

Pingback from  SharePoint 2007 Link List  &laquo; Prashant Jadhav

Mahdi wrote re: Create custom field types for SharePoint
on 12-14-2008 9:04 AM

Thanks

h.mehrpooya wrote re: Create custom field types for SharePoint
on 12-28-2008 11:41 PM

Hi Nick

I'm trying to have a new calendar in sharepoint.I have some ways in my mind.it would be very kind of you to help me find the way

I could create a new date column as you said in sharepoint and change all the stored procedures in sql that select the data for sharepoint lists

the other way is to create a calendar for windows i mean change one of the current ones but i'm not sure what to do please help me out

create custom field types for sharepoint « Gianluca Bosco’s Blog wrote create custom field types for sharepoint &laquo; Gianluca Bosco&#8217;s Blog
on 01-18-2009 11:20 AM

Pingback from  create custom field types for sharepoint &laquo; Gianluca Bosco&#8217;s Blog

Prat wrote re: Create custom field types for SharePoint
on 02-16-2009 3:27 AM

Nick,

Any luck on SPFieldLookup (with multiple values)

Appreciate if  you can post some code.

Iam trying to populate treeview and use an SPFieldLookUp (multi).

Need your help

Prat

Rahul wrote re: Create custom field types for SharePoint
on 02-24-2009 11:45 AM

A Good one

While I am trying to create a custom field which store the value such as webservice url or any other string.

Any Help will be helpfull, if u can.

Yashwant wrote re: Create custom field types for SharePoint
on 03-17-2009 6:26 AM

Hi,

I have created Same Field with exact same code but getting folloing error.

"The given assembly name or codebase was invalid. (Exception from HRESULT: 0x80131047) "

sacchit wrote re: Create custom field types for SharePoint
on 03-18-2009 2:20 AM

Issue of saving the  custom field type values through dataformwepart (custom list form webpart).

Tom wrote re: Create custom field types for SharePoint
on 03-24-2009 10:20 AM

Many thanks for an awesome post - it really has been useful. I've managed to implement the custom field control in MOSS and succesfully hooked it up to a content type.

I'd like to be able to use this field in my page layout, however it complains that it doesn't recognise the server tag. I've tried dragging and dropping the field from the list of content fields using SPD which automatically generates the required markup ie:

<CustomTag_0:customfieldcontrol ID="NameControl" FieldName="test" runat="server"></CustomTag_0:customfieldcontrol>

I then inserted a Register statement at the top of the pagelayout:

<%@ Register TagPrefix="CustomTag_0"

Namespace="CustomField.CustomField",

Assembly="CustomField, Version=0.0.0.0, Culture=neutral, PublicKeyToken=91e52169c28db0da" %>

Any ideas where I may be going wrong?!

Dave wrote re: Create custom field types for SharePoint
on 04-30-2009 6:23 AM

Has anyone been able to figure out how to make the fields editable in the datasheet view?

Rich Browne wrote re: Create custom field types for SharePoint
on 05-06-2009 6:00 PM

Hey guys, just happened upon this post whilst doing some custom field type development.

To answer an earlier query that Erin raised, the issue is caused by the GetValidatedString function - this function is not called on display as you thought, but is called when setting the value of the field (i.e. saving the modified list item), the return value of which is the value saved to the field. This is why when editing the field again, the value appears only in the first textbox, because there is no % to split by.

There are two possible solutions to this problem:

1.) Modify the Value property in customfieldcontrol to not insert % and split at first space (could introduce issues if the user enters a space in the first textbox though)

2.) Use a render pattern displaypattern to alter the displayed value in all items view.

As far as I know, there is no other way besides render patterns with which to alter the displayed value of a field to be different to it's stored value.

Hope this helps!

Add a Comment

(required)  
(optional)
(required)  
Remember Me?
Need SharePoint Training? Attend a SharePoint Bootcamp!
Posts (c) their respective authors. Everything else (c) 2009 SharePoint Experts, Inc.