пятница, 17 июля 2009 г.

Sharepoint Unique Column (PK) : Using event handler

Оригинал тут:

http://jpy-tech.com/blog/post/Sharepoint-Unique-Column-%28PK%29-Using-event-handler.aspx

Задача: Обеспечить уникальное значение поля.

Решение: Написать EventHandler и внести логику для проверки введенного значения.

Исходный код немного кривоват так что используйте поправленный мною вариант.

Пояснения, после установки этого обработчика, достаточно будет добавить в описание поля метку [$UNIQUE$] и это поле будет проверяться на уникальность.

const string _QUERY = @"<Where><Eq><FieldRef Name=""{0}"" /><Value Type=""Text"">{1}</Value></Eq></Where>"; public override void ItemAdding(SPItemEventProperties properties) { using (SPWeb web = properties.OpenWeb()) { /*get the current list*/ SPList list = web.Lists[properties.ListId]; string columnName = ""; foreach (SPField fld in list.Fields) { if (fld.Description.Contains("[$UNIQUE$]")) { columnName = fld.InternalName; break; } }

if (properties.AfterProperties[columnName] != null) { string currentValue = properties.AfterProperties[columnName].ToString(); SPQuery _query = new SPQuery(); _query.Query = string.Format(_QUERY, columnName, currentValue); SPListItemCollection itemsWithSameValue = list.GetItems(_query); if (itemsWithSameValue.Count > 0) { properties.Cancel = true; properties.ErrorMessage = "There is already an item with the same value(" + currentValue + ") for the column / Field(" + columnName + ") in this list."; } } } }

1 комментарий:

Prince P Y комментирует...

please change the link to "http://jpy-tech.com/blog/post/Sharepoint-Unique-Column-%28PK%29-Using-event-handler.aspx" from jpy-tech.com administrator