Saturday, October 1, 2011

Create a unique value field in Sharepoint 2007

Hi all,
Many times the most common requirement is such that we have to build custom field in SharePoint and hence I though of sharing information on how we can create custom fields. I am going to share this interesting feature because there is so much fun in it to learn so many techniques while creating custom field.
In this post, I will create a custom field that grants user from entering duplicated values in this field.
Before diving more into coding part, first let me give you highlight on what all files are necessary for this.1) Control ascx file - This is required for the field that we are going to develop; this will actually play a role while assigning field to the actual type (textbox, drop down etc).
2) Control xml file - This will define the type of the field and register to the SharePoint to make it understand that there is some field type that needs to be rendered at the time of creating field. We can define much more here. We will see them in upcoming series.
3) Control cs file – Coding related to the control which tells SharePoint about getting and setting the value of field and also to assign properties to the control in the code.
4) Field file – To validate the value entered in the field and throw the exception if validation fails. This will prevent item being added in the list. At the end, if we do not want any validation to happen, this file can return the value which is entered in the field.
Now let’s start,
Open Visual Studio and create a project with appropriate name to you. Now add one file and its extension should be .ascx. Make sure that you reference System.Web and Microsoft SharePoint assembly in the project.Type in below code in that.
<%@Control Language=”C#” Debug=”true”%>
<%@Assembly Name=”Microsoft.SharePoint, Version=12.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c” %>
<%@Register TagPrefix=”SharePoint” Assembly=”Microsoft.SharePoint, Version=12.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c” namespace=”Microsoft.SharePoint.WebControls”%>
<SharePoint:RenderingTemplate ID=”SPUniqueColumnTextbox” runat=”server”>
<Template>
<asp:TextBox ID=”txtTextBox” runat=”server” />
</Template>
</SharePoint:RenderingTemplate>

You can give your own ID to the rendering template and your own ID to textbox control.Now add one more file. Call it as an xml file. And then type in the following code in it.
<?xml version=”1.0″ encoding=”utf-8″ ?>
<FieldTypes>
  <FieldType>
    <Field Name=”TypeName”>SPUnique Field</Field>
    <Field Name=”TypeDisplayName”>SPUnique Field</Field>
    <Field Name=”TypeShortDescription”>SPUnique Field</Field>
    <Field Name=”ParentType”>Text</Field>
    <Field Name=”FieldTypeClass”>CustomColumn.SPUniqueField, CustomColumn, Version=1.0.0.0, Culture=neutral, PublicKeyToken=aa9abbe34842e666</Field>
    <Field Name=”Sortable”>TRUE</Field>
    <Field Name=”Filterable”>TRUE</Field>
  </FieldType>
</FieldTypes>

Now let me explain you each tag here. We will explore more and more tag in upcoming series.
- First the Type Name is the name that you want to give to this field. 
- Type Display Name is the name of the field that will appear when you add the column to the list. 
- Type Short Description as a name suggest is the description about this field. 
Parent Type is also an interesting value. We will see more on this in upcoming series. As of now we have taken it as Text. 
FieldTypeClass is the entire assembly reference with the field class name. We are going to add field class soon. SPUniqueField is the name of the field class in my project. 
Sortable true means you are allowing your end user to sort this column in list view web part and on AllItems and EditItems page. If this is false, they cannot sort this field. 
Filterable means filter can appear in that field column. If specified false, then you cannot filter on that column.
Change the appropriate references for your project assembly wherever it applies.Add one more class and name it according to your choice. And paste the following code in it. I have demonstrated whole class file with namespace. This class is Control class for our custom field. Change your references accordingly. Make sure that your default template name should be equal to the rendering template id that you have in the ascx file. And your protected textbox ID should be equal to the textbox id that you gave in ascx file.
using System;
using System.Collections.Generic;
using System.Text;
using System.Web.UI.WebControls;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;

namespace CustomColumn
{
    public class SPUniquieColumnControl : BaseFieldControl
    {
        protected TextBox txtTextBox;        
        protected override string DefaultTemplateName
        {
            get
            {
                return @”SPUniqueColumnTextbox”;
            }
        }
        
        public override object Value
        {
            get
            {
                EnsureChildControls();
                return txtTextBox.Text.Trim();
            }

            set
            {
                EnsureChildControls();
                txtTextBox.Text = (string)this.ItemFieldValue;
            }
        }
        
        protected override void CreateChildControls()
        {
            if (Field == null) return;
            base.CreateChildControls();
        }
    }
}


As you can see override Value method actually does the work of getting and setting the value of the field.Now add one more class name it according to your choice. This is the field class for our custom field. And write down the following code. I have taken namespace and class of my project in this reference code. Change it to your own need.

using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
namespace CustomColumn
{
    public class SPUniqueField : SPFieldText
    {
        #region Contstructors
        public SPUniqueField(SPFieldCollection fields, string fieldName)
        : base(fields, fieldName)
        {
        }
        public SPUniqueField(SPFieldCollection fields, string typeName, string displayName)
        : base(fields, typeName, displayName)
        {
        }
        #endregion
        public override string GetValidatedString(object value)
        {
            string strTxtValue = Convert.ToString(value).Trim();
            SPList thisList = ParentList;
            SPQuery keywordQuery = new SPQuery();
            // Check to see if the current field contains the value entered into field
            keywordQuery.Query = string.Format(“<Where>” +
                     “<Eq>” +
                        ”<FieldRef Name=’{1}’ />” +
                        ”<Value Type=’Text’>{0}</Value>” +
                     “</Eq>” +
               “</Where>”, value, InternalName);
            SPListItemCollection liKeywords = thisList.GetItems(keywordQuery);
            // Will return greater than 0 if it finds the value in the list
            if (liKeywords.Count > 0)
            {
                // checks to see if the list item is being updated, if it is the same finds the same ID as the one being Validated
                if (liKeywords[0].ID != SPContext.Current.ItemId)
                {
                    // Show error message
                    throw new SPFieldValidationException(string.Format(“An item called ‘{0}’ already exists”, value));
                }
            }
            // return entered value if unique
            return base.GetValidatedString(value);
        }
    }
}
Deploy the solution to your Sharepoint site and you will see the result as the following video:






www.sharepointkings.com

0 comments:

Post a Comment

Twitter Delicious Facebook Digg Stumbleupon Favorites More

 
Design by Free WordPress Themes | Bloggerized by Lasantha - Premium Blogger Themes | Affiliate Network Reviews