Search This Blog

2011-02-24

Create a custom Field in Sharepoint 2007

Step 1-Create a class libary Project "CustomField_TelephoneNumber"

Step 2--Create the folder structure and add reference as follows-


Step 3-"TelephoneFieldControl.ascx" will be as follows-

<%@ 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="TelephoneFieldControl" runat="server">
<Template>

<script language="javascript">
<!-- This script is based on the javascript code of Roman Feldblum (web.developer@programmer.net) -->
<!-- Original script : http://javascript.internet.com/forms/format-phone-number.html -->
<!-- Original script is revised by Eralper Yilmaz (http://www.eralper.com) -->
<!-- Revised script : http://www.kodyaz.com -->

var zChar = new Array(' ', '(', ')', '-', '.');
var maxphonelength = 13;
var phonevalue1;
var phonevalue2;
var cursorposition;

function ParseForNumber1(object){
phonevalue1 = ParseChar(object.value, zChar);
}

function ParseForNumber2(object){
phonevalue2 = ParseChar(object.value, zChar);
}

function backspacerUP(object,e) {
if(e){
e = e
} else {
e = window.event
}

if(e.which){
var keycode = e.which
} else {
var keycode = e.keyCode
}

ParseForNumber1(object)
if(keycode > 48){
ValidatePhone(object)
}
}


function backspacerDOWN(object,e) {
if(e){
e = e
} else {
e = window.event
}

if(e.which){
var keycode = e.which
} else {
var keycode = e.keyCode
}

ParseForNumber2(object)
}

function GetCursorPosition(){
var t1 = phonevalue1;
var t2 = phonevalue2;
var bool = false
for (i=0; i<t1.length; i++)
{
if (t1.substring(i,1) != t2.substring(i,1)) {
if(!bool) {
cursorposition=i
bool=true
}
}
}
}


function ValidatePhone(object){



var p = phonevalue1



p = p.replace(/[^\d]*/gi,"")



if (p.length < 3) {

object.value=p

} else if(p.length==3){

pp=p;

d4=p.indexOf('(')

d5=p.indexOf(')')

if(d4==-1){

pp="("+pp;

}

if(d5==-1){

pp=pp+")";

}

object.value = pp;

} else if(p.length>3 && p.length < 7){

p ="(" + p;

l30=p.length;

p30=p.substring(0,4);

p30=p30+")"



p31=p.substring(4,l30);

pp=p30+p31;



object.value = pp;



} else if(p.length >= 7){

p ="(" + p;

l30=p.length;

p30=p.substring(0,4);

p30=p30+")"



p31=p.substring(4,l30);

pp=p30+p31;



l40 = pp.length;

p40 = pp.substring(0,8);

p40 = p40 + "-"



p41 = pp.substring(8,l40);

ppp = p40 + p41;



object.value = ppp.substring(0, maxphonelength);

}



GetCursorPosition()



if(cursorposition >= 0){

if (cursorposition == 0) {

cursorposition = 2

} else if (cursorposition <= 2) {

cursorposition = cursorposition + 1

} else if (cursorposition <= 5) {

cursorposition = cursorposition + 2

} else if (cursorposition == 6) {

cursorposition = cursorposition + 2

} else if (cursorposition == 7) {

cursorposition = cursorposition + 4

e1=object.value.indexOf(')')

e2=object.value.indexOf('-')

if (e1>-1 && e2>-1){

if (e2-e1 == 4) {

cursorposition = cursorposition - 1

}

}

} else if (cursorposition < 11) {

cursorposition = cursorposition + 3

} else if (cursorposition == 11) {

cursorposition = cursorposition + 1

} else if (cursorposition >= 12) {

cursorposition = cursorposition

}



var txtRange = object.createTextRange();

txtRange.moveStart( "character", cursorposition);

txtRange.moveEnd( "character", cursorposition - object.value.length);

txtRange.select();

}



}



function ParseChar(sStr, sChar)

{

if (sChar.length == null)

{

zChar = new Array(sChar);

}

else zChar = sChar;



for (i=0; i<zChar.length; i++)

{

sNewStr = "";



var iStart = 0;

var iEnd = sStr.indexOf(sChar[i]);



while (iEnd != -1)

{

sNewStr += sStr.substring(iStart, iEnd);

iStart = iEnd + 1;

iEnd = sStr.indexOf(sChar[i], iStart);

}

sNewStr += sStr.substring(sStr.lastIndexOf(sChar[i]) + 1, sStr.length);



sStr = sNewStr;

}



return sNewStr;

}

</script>

<asp:TextBox ID="txtNumber" runat="server" MaxLength="15" Size="20" onkeydown="javascript:backspacerDOWN(this,event);"
onkeyup="javascript:backspacerUP(this,event);" />
</Template>
</SharePoint:RenderingTemplate>


Step 4-"FLDTYPES_Telephone.xml" will be as follows-

<?xml version="1.0" encoding="utf-8"?>
<FieldTypes>
<FieldType>
<Field Name="TypeName">PhoneNumber</Field>
<Field Name="ParentType">Text</Field>
<Field Name="TypeDisplayName">Phone Number</Field>
<Field Name="TypeShortDescription">Phone Number</Field>
<Field Name="UserCreatable">TRUE</Field>
<Field Name="ShowInListCreate">TRUE</Field>
<Field Name="ShowInSurveyCreate">TRUE</Field>
<Field Name="ShowInDocumentLibraryCreate">TRUE</Field>
<Field Name="ShowInColumnTemplateCreate">TRUE</Field>
<Field Name="FieldTypeClass">CustomField_TelephoneNumber.TelephoneField,CustomField_TelephoneNumber, Version=1.0.0.0, Culture=neutral, PublicKeyToken=30534ee939de1c1d</Field>
<!-- We will implement this later to add display formating for the fields value. ie (xxx)xxx-xxxx
<RenderPattern Name="DisplayPattern">
<Switch>
<Expr>
<Column />
</Expr>
<Case Value="" />
<Default>
<HTML><![CDATA[^]]></HTML>
<Column HTMLEncode="TRUE" />
</Default>
</Switch>
</RenderPattern>
-->
</FieldType>
</FieldTypes>


Step 5-"TelephoneField.cs" will be as follows-

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint;
using System.Text.RegularExpressions;

namespace CustomField_TelephoneNumber
{
//Should inherit from an existing SPField class
public class TelephoneField : SPFieldText
{
#region Contstructors
public TelephoneField(SPFieldCollection fields, string fieldName)
: base(fields, fieldName)
{

}
public TelephoneField(Microsoft.SharePoint.SPFieldCollection fields, string typeName, string displayName)
: base(fields, typeName, displayName)
{

}

#endregion

public override Microsoft.SharePoint.WebControls.BaseFieldControl FieldRenderingControl
{
get
{
Microsoft.SharePoint.WebControls.BaseFieldControl phoneNumberFieldControl = new TelephoneFieldControl();
phoneNumberFieldControl.FieldName = InternalName;
return phoneNumberFieldControl;
}
}
/// <summary>
/// This method validates the data as it is entered into the column. If it doesnt match the criteria a sharepoint exception is thrown.
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
public override string GetValidatedString(object value)
{
string myVal = value as string;
if (myVal == null)
return String.Empty;

//Strip formating characters from the value..
myVal = myVal.Replace("(", "");
myVal = myVal.Replace(")", "");
myVal = myVal.Replace("-", "");
myVal = myVal.Replace("+", "");
myVal = myVal.Replace(" ", "");
myVal = myVal.Trim();

//Use regex to makes the string only contains numbers and is within the correct range.
Regex foo = new Regex("^\\d{10,11}$");
if (foo.IsMatch(myVal))
{

}

else
{
throw new Microsoft.SharePoint.SPFieldValidationException("The Telephone number field must contain only numbers, (, ), -, or + characters. It must also be between 10 and 11 digits. val:" + myVal);
}
return myVal;
}
/// <summary>
/// Here we can apply formating to our number that will show up on the edit page.
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
public override object GetFieldValue(string value)
{
if (String.IsNullOrEmpty(value))
return null;
//TODO - Format the phone number here (XXX)XXX-XXXX
return value;
}
}
}


Step 6-"TelephoneFieldControl.cs" will be as follows-

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.UI.WebControls;
using Microsoft.SharePoint.WebControls;
//http://www.sharethispoint.com/archive/2006/08/07/23.aspx#codethree

namespace CustomField_TelephoneNumber
{
class TelephoneFieldControl : BaseFieldControl
{
protected TextBox txtNumber;
//The DefaultTemplateName property lets sharepoint know which rendering template to use this class for.
protected override string DefaultTemplateName
{
get
{
return "TelephoneFieldControl";
}
}

//The value property controls how the data that SharePoint provides gets parsed into our control
public override object Value
{
get
{
EnsureChildControls();
return txtNumber.Text.Trim();
}
set
{
EnsureChildControls();
txtNumber.Text = (string)this.ItemFieldValue;
}
}

public override void Focus()
{
EnsureChildControls();
txtNumber.Focus();
}

protected override void CreateChildControls()
{
if (Field == null) return;
base.CreateChildControls();
if (ControlMode == Microsoft.SharePoint.WebControls.SPControlMode.Display)
return;

txtNumber = (TextBox)TemplateContainer.FindControl("txtNumber");
if (txtNumber == null)
throw new ArgumentException("txtNumber is null. Corrupted TelephoneFieldControl.ascx file.");

txtNumber.TabIndex = TabIndex;
txtNumber.CssClass = CssClass;
txtNumber.ToolTip = Field.Title + " Phone Number";
}
}
}

Step 7-Attach the strong name & Copy the dll to GAC.

Step 8-Copy the files to their respective folder as folder structure in the project.

Step 9-Reset IIS

Step 10-Create a Custom list in sharepoint 2007 and add your custome field column to the list.



Step 11-Add item to your Custom List

No comments: