Thursday, June 29, 2006

How to make lookup field to retrieve the field value rather than item name


How to make lookup field to retrieve the field value rather than item name For example, you want to refer to the Country items from your custom lookup field: content ---home -------countries ----------------Ukraine ----------------Denmark ----------------Germany ----------------USA ----------------Spain If you specify just a source field of your template field as /content/countries, you will get this field populated with the item names. But there is also a possibility to retrieve the field values of these items rather that the names. Let’s assume that these items are based on the Country template that defines a single field named ISO: If you want to have a custom lookup field populated with the ISO field values instead of the item’s name, the following steps should be completed: Add the custom lookup field named List to e.g. Document template: Extend the Template field template by adding a field named Field Name which will define the name of the field to fill into the lookup dropdown list: Fill the newly created field with the ISO value – name of the field to retrieve the values from: Now you have to customize the source code of your custom lookup field. Here is the full source code of the custom lookup field. The instructions about how to add a custom field to Sitecore shell can be found here: http://sdn5.sitecore.net/Articles/API/ Creating%20a%20Composite%20Custom%20Field/ Adding%20a%20Custom%20Field%20to%20Sitecore%20Client.aspx using System; using System.Text; using Sitecore; using Sitecore.Data; using Sitecore.Data.Items; using Sitecore.Shell.Applications.ContentEditor; using Sitecore.Web.UI.Sheer; using Sitecore.Web.UI.HtmlControls; using Sitecore.Web.UI.HtmlControls.Data; namespace Sitecore.Shell.Applications.ContentEditor { public class CustomLookup : Lookup { protected override void OnLoad(EventArgs args) { if (!Sitecore.Context.ClientPage.IsEvent) { Item contextItem = Sitecore.Context.ContentDatabase.Items[this.ItemID]; foreach(TemplateFieldItem tfItem in contextItem.Template.OwnFields) { if(tfItem.Source == this.Source) { FieldName = tfItem.InnerItem.Fields["Field Name"].Value; } } } base.OnLoad(args); } } } Here we have overridden the OnLoad method with the code that sets the FieldName property to the value of the field. There are some tricks made here since we do not know the name of the current field (List in our case), we had to iterate thorough the template’s own field of the context item and check the Source property. If the sources match, the FieldName property is set to the value of the template field (ISO in our case). The result of the actions above are depicted below: