The contact selector control in InfoPath makes implementing a user/group lookup field quite easy. However, there are a few downsides.
Ben Walters has done a very nice job of listing the upsides and downsides to using this control in his post,
Contact Selector the Good and the Bad.
The one aspect of InfoPath (2003) that prevented company wide deployment at my employer was the need to have the InfoPath client in order to fill out a form. Now that Microsoft has implemented Forms Server and allowed the filling of forms via a web browser, many of my colleagues have been banging at my door for custom InfoPath solutions.
The requirement that I have been presented with was to use the Contact Selector control, to make it required, and to only allow one value. After reading the above post by Ben, which references some validation code posted in a comment on the
InfoPath Team blog, it became apparent there was no easy solution for browser-based forms.
Below I offer my solution:
- Domain trust form
- No digital certificate
public void InternalStartup()
{
EventManager.FormEvents.Loading +=
new LoadingEventHandler(FormEvents_Loading);
EventManager.XmlEvents["/my:myFields/my:contactSelector"].Changed +=
new XmlChangedEventHandler(contactSelector_Changed);
}
public void FormEvents_Loading(object sender, LoadingEventArgs e)
{
XPathNavigator mainDS = this.MainDataSource.CreateNavigator();
if (this.New)
{
XPathNavigator contSel =
mainDS.SelectSingleNode("/my:myFields/my:contactSelector",
NamespaceManager);
this.Errors.Add(contSel, "ContactSelectorError",
"You must select a contact.");
return;
}
}
public void contactSelector_Changed(object sender, XmlEventArgs e)
{
if (e.Site.SelectChildren(XPathNodeType.Element).Count == 1)
{
try
{
this.Errors.Delete("ContactSelectorError");
}
catch { }
}
if (e.Site.SelectChildren(XPathNodeType.Element).Count > 1)
this.Errors.Add(e.Site, "ContactSelectorError",
"Only one contact can be selected.");
if (e.Site.SelectChildren(XPathNodeType.Element).Count < 1)
this.Errors.Add(e.Site, "ContactSelectorError",
"You must select a contact.");
}
Some notes:
Enjoy!
--andrew