PART 2 : Coding in InfoPath


For better understanding, please read PART 1 before proceeding further.

SCENARIO – Course Registration form

Course registration form contains four fields: Employee ID, Course Name, Course start  Date(Mandatory) and Course End Date(Mandatory)

course Registration Form

Let’s try to write code for

  • Validation on Employee Id text box to accept only numbers and must be of 6 digits
  • Validation on course name on button click
  • Submit the data and Switch to thank you page once validation is completed
  • Exit the application

Validation on Employee Id text box to accept only numbers and must be 6 digits:

Points to Note:

  • Validation message is shown only when Employee ID is edited for validating Event. If Employee ID is left blank, InfoPath throws the error, “An unhandled exception has occurred in the Form’s code” on submit button click.
  • Suppose validation is not applied under ValueChange condition (if (e.Operation == XmlOperation.ValueChange)), message dialog box will be shown once the form is loaded. Hence, do not use message dialog box for validating event as screen tip is already shown via the line e.ReportError(e.Site, true, “Please enter 6 digits”). Only if dialog box is necessary, use the condition to check on value change.
  • You may ask me, why should I apply in validating event and then check on value change rather than directly checking on changed event as shown below
public void EmployeeID_Changed(object sender, XmlEventArgs e)
{
 System.Text.RegularExpressions.Regex reg = new System.Text.RegularExpressions.Regex("^[0-9]{6}$");
XPathNavigator xpn = this.MainDataSource.CreateNavigator();
string fiels1 = xpn.SelectSingleNode("/my:myFields/my:EmployeeID", this.NamespaceManager).Value;
if (!reg.IsMatch(fields1))
    {
         MessageBox.Show("Please enter 6 digits", "system message", MessageBoxButtons.OK, MessageBoxIcon.Error);
    }
}

Yes, it depends on your requirement. Validating event is used for Validation that shows red dotted line when the condition is not met and changed event is triggered on value change.

public void EmployeeID_Validating(object sender, XmlValidatingEventArgs e)
{
  //Validate on value change
  if (e.Operation == XmlOperation.ValueChange)
   {
      //Regular expression to check for 6 digit number
     System.Text.RegularExpressions.Regex reg = new System.Text.RegularExpressions.Regex("^[0-9]{6}$");
     XPathNavigator xpn = this.MainDataSource.CreateNavigator();
     string fields1 = xpn.SelectSingleNode("/my:myFields/my:EmployeeID", this.NamespaceManager).Value;
     if (!reg.IsMatch(fields1)) //if regular expression does not match
      {
           e.ReportError(e.Site, true, "Please enter 6 digits");
           MessageBox.Show("Please enter 6 digits","system message",MessageBoxButtons.OK,MessageBoxIcon.Warning);
      }
  }
}

Validation message

Validation on course name on button click

//Validating if course name is blank on Submit button click
public void CTRL6_5_Clicked(object sender, ClickedEventArgs e)
{
  XPathNavigator xpn = this.MainDataSource.CreateNavigator();
  string course = xpn.SelectSingleNode("/my:myFields/my:CourseName",this.NamespaceManager).Value;
//checking if course name is empty using the length of the text
  if (course.Length == 0)
  MessageBox.Show("Please enter the course name");
}

Course Name error

You may also apply all the conditions in button click based on your requirement.

public void CTRL6_5_Clicked(object sender, ClickedEventArgs e)
{
  XPathNavigator xpn = this.MainDataSource.CreateNavigator();
  string course = xpn.SelectSingleNode("/my:myFields/my:CourseName",this.NamespaceManager).Value;
  string EmpID = xpn.SelectSingleNode("/my:myFields/my:EmployeeID", this.NamespaceManager).Value;
  System.Text.RegularExpressions.Regex reg = new System.Text.RegularExpressions.Regex("^[0-9]{6}$"); 
  if (course.Length == 0)
       MessageBox.Show("Please enter the course name");
else if (!reg.IsMatch(EmpID))
        MessageBox.Show("Please enter 6 digits for Employee ID");  
else
    {
         DataConnection subconn = DataConnections["SharePoint Library Submit"];
       subconn.Execute();
        this.ViewInfos.SwitchView("Thank you");
     }
}

To validate on default submit, please write in FormEvents_Submit handler.

public void FormEvents_Submit(object sender, SubmitEventArgs e)
{
XPathNavigator xpn = this.MainDataSource.CreateNavigator();
string course = xpn.SelectSingleNode("/my:myFields/my:CourseName", this.NamespaceManager).Value;
if (course.Length == 0)
{
 e.CancelableArgs.Message = "Please enter the course name";
 e.CancelableArgs.Cancel = true;
}
else
{
DataConnection subconn = DataConnections["SharePoint Library Submit"];
subconn.Execute();
e.CancelableArgs.Message = "The form was submitted successfully";
e.CancelableArgs.Cancel = false;
this.ViewInfos.SwitchView("Thank you");
}
}

Submit the data and Switch to thank you page once validation is completed

public void CTRL6_5_Clicked(object sender, ClickedEventArgs e)
{
XPathNavigator xpn = this.MainDataSource.CreateNavigator();
string course = xpn.SelectSingleNode("/my:myFields/my:CourseName",this.NamespaceManager).Value;
if (course.Length == 0)
MessageBox.Show("Please enter the course name");
else
{
DataConnection subconn = DataConnections["SharePoint Library Submit"];
subconn.Execute();
this.ViewInfos.SwitchView("Thank you");
}
}

Thank you Form

Exit the application on button click

//Exits the InfoPath application
public void CTRL1_9_Clicked(object sender, ClickedEventArgs e)
{
System.Environment.Exit(0);
}

code:

namespace Form1
{
public partial class FormCode
{
//All the events are initialized in internal startup automaticallypublic void InternalStartup()
{
 ((ButtonEvent)EventManager.ControlEvents["CTRL6_5"]).Clicked += new ClickedEventHandler(CTRL6_5_Clicked);
 EventManager.XmlEvents["/my:myFields/my:EmployeeID"].Validating += new XmlValidatingEventHandler(EmployeeID_Validating);
 EventManager.FormEvents.Submit += new SubmitEventHandler(FormEvents_Submit);
 ((ButtonEvent)EventManager.ControlEvents["CTRL1_9"]).Clicked += new ClickedEventHandler(CTRL1_9_Clicked);
}

public void CTRL6_5_Clicked(object sender, ClickedEventArgs e)
{
XPathNavigator xpn = this.MainDataSource.CreateNavigator();
string course = xpn.SelectSingleNode("/my:myFields/my:CourseName",this.NamespaceManager).Value;
if (course.Length == 0)
MessageBox.Show("Please enter the course name");
else
{
DataConnection subconn = DataConnections["SharePoint Library Submit"];
subconn.Execute();
this.ViewInfos.SwitchView("Thank you");
}
}
public void EmployeeID_Validating(object sender, XmlValidatingEventArgs e)
{
if (e.Operation == XmlOperation.ValueChange)
{
 System.Text.RegularExpressions.Regex reg = new System.Text.RegularExpressions.Regex("^[0-9]{6}$");
XPathNavigator xpn = this.MainDataSource.CreateNavigator();
string fiels1 = xpn.SelectSingleNode("/my:myFields/my:EmployeeID", this.NamespaceManager).Value;
if (!reg.IsMatch(fiels1))
{
 e.ReportError(e.Site, true, "Please enter 6 digits");
MessageBox.Show("Please enter 6 digits","system message",MessageBoxButtons.OK,MessageBoxIcon.Hand);
}
}
}

public void FormEvents_Submit(object sender, SubmitEventArgs e)
{
//code for default submit data connection
}
public void CTRL1_9_Clicked(object sender, ClickedEventArgs e)
{
 System.Environment.Exit(0);
}
}
}
Advertisements

PART 1 – Coding in InfoPath


Hi! I am back with an article on InfoPath again. When someone says, you are an InfoPath expert, I say with sad face “No, I do not know about InfoPath Code behind and Digital Signatures”. No more worries on InfoPath Code behind. Thanks to my lead who introduced me to the world of InfoPath code behind.

Before going through the steps for code behind , make a note that coding can be done only in (InfoPath)Form library and not in List forms. Let us see how to create code behind file in InfoPath.

CREATING CODE BEHIND FILE:

  • Click on File tab -> Form Options(Advanced form options). In Form Options dialog box, click on Programming on left and choose the form template code language as shown below

(or)

  •  Go to Developer tab, click on Language and select the language/Change Language

  • Click on Code Editor(located next to Language in Developer tab) to see the FormCode.cs file(code behind file)
  • To write code for a button click, right click on the button ->Button Properties…->Edit form Code

Microsoft Visual Studio Tools for Applications opens as shown below

  • To validate a field or to set some action when the field’s value is changed, use the Validating event/Changed event in Programming  in fields pane or in Control Events section in developer tab

Control Events

So far, we have seen how to add code in InfoPath. Now, let us see the basic syntax/code

InfoPath is a xml file where all the fields are saved as xml nodes. To select or navigate to the nodes, XPathNavigator is used.

To get a field value in InfoPath, syntax goes as:

XPathNavigator xpn = this.MainDataSource.CreateNavigator();
string fn = xpn.SelectSingleNode(“XPATH OF THE FIELD“, this.NamespaceManager).Value;

To set a field value in InfoPath, syntax is

XPathNavigator xpn = this.MainDataSource.CreateNavigator();
XPathNavigator temp = xpn.SelectSingleNode(“XPATH OF THE FIELD, this.NamespaceManager); temp.SetValue(“Hello Sathiya”);

If you notice the above syntax, the first argument of SelectSingleNode is xpath of a field. To find the xpath of a field:

  • Go to Fields pane, click on down arrow dropdown of a field and select Copy Xpath as depicted below

To query or submit data connection, syntax is

DataConnection submitConn = DataConnections[“DATA CONNECTION NAME“];
submitConn.Execute();

To switch among the views, syntax is:

this.ViewInfos.SwitchView(“Thank you”);

 

With these basics, we will try to do magic 😛 in InfoPath form in the upcoming article 🙂

InfoPath Preview to the rescue


In this post, let’s see about Preview option in InfoPath. It is not always recommended or necessary to publish the changes in order to verify it. To verify the changes made in InfoPath, use the preview option.

Preview for New forms:

Let us assume you are designing a new form and you want to verify then and there. Instead of publishing the changes every time, use the below steps:

  • Click on Home tab in InfoPath ribbon (if the current tab is not Home)
  • Click on Preview in Form section as shown below

Preview for new forms

Preview for Existing forms:

What if you are making an enhancement to the exiting form and would like to know how it behaves for already submitted form. Please follow the below steps to verify the behavior:

  • Go to the form library, select the submitted form and click on Download a copy in the ribbon as shown below

Download a copy

  • Go to InfoPath Design form and click on File->Form Options(Advanced Form Options)

Form Options

  • In Form options, click on Preview, browse the downloaded form under Sample data and click ok

Preview for Existing forms

  • Click on Home tab->Preview in Form section to see the changes in submitted form
  • If you have assigned User roles to the InfoPath form, you can change the user role to preview the submitted form as depicted below

Preview using different user roles

Repeating Table – set color for alternative rows and auto number the rows


Set color for alternative rows:

Logic behind : Odd number of rows(1,3,5,7..) when divided by 2 will return the remainder 1  and even number of rows(2,4,6,8..) when divided by 2 will return the remainder 0. To find the remainder, we use mod(modulo) operator. To find whether the row is odd number or even number, we can use position() in infopath.

  • Go to Home->Manage rules
  • In fields pane, select the group containing repeating fields and add formatting rule
  • Under condition, click on None and select “The expression” in first drop down
  • To color the odd rows, enter the expression as position() mod 2 > 0 or position() mod 2 = 1
  • Under Formatting, select the color that you would like to apply in Shading(bucket symbol)

Color alternative rows

  • Click on Home->Preview to see the result

Auto number repeating table rows:

  • To auto generate number in SNO inside repeating table, right click on SNO ->Text Box Properties
  • Under Default values, click on fx and insert the formula, count(../preceding-sibling::my:group2) + 1 and click ok

  • You can also use position() instead of the above formula but this will not be supported in InfoPath 2013 text box. However, it can be used in Calculated value in InfoPath 2013. Right click the SNO ->Change Control->Calculated Value and enter position() in XPath

  • Click on Home -> Preview to see the result.

 

Repeating Table – Set default number of rows and limit the total number of rows


Repeating table plays a vital role in form library to insert several rows of data in a single form. In this post, let’s see two different methods of setting the default number of rows and limiting the total number of rows in repeating table.

METHOD 1 – Using Default Values and Rules

Set default number of rows:

  • Go to Data tab in the ribbon and click on Default Values
  • In Edit Default values dialog box, right click on group that contains the repeating table fields and select “Add another group below”. Repeat this step to increase the default number of rows
  • Click on Home->Preview to see the result.

  • Limitation – You will not be able to remove the rows inserted by this method

Limit total number of rows:

  • Go to Home tab and click on Manage rules
  • Select the group(group2 in above picture) that contains repeating fields in Fields pane
  • In Rules pane, click on New -> Formatting
  • Under condition, select “The expression” in first drop down, type the expression value as count(/my:myFields/my:group1/my:group2) = 6
  • Under Formatting, tick the box “Don’t allow users to insert or delete this control” as depicted below

  • Now, when the user inserts the 6th row and click on insert item, rows will not be created and drop down highlighted below shown till 5th row will disappear on inserting 6th row to prevent insertion and deletion.

METHOD 2: (Modifying the Source File)

  • After designing the form with repeating table, click on Publish -> Export Source Files

  • Browse the location and type the folder name to save the source file

  • Close the InfoPath form and open “myschema.xsd” from source file folder

  • To set default number of rows, change the minOccurs value as shown below
  • To limit the total number of rows, change the maxOccurs value as shown below

  • Save myschema.xsd and close it
  • Open manifest file in Design mode, preview and publish it
  • Now, when the user tries to insert 11th row, below error will be shown.

Link to Email in InfoPath form


We all know how to create a link to an email in html page using the anchor tag. Do you know that the same is possible in InfoPath Form? Yes, we can do the same in infopath form in much simpler way. Here are the steps:

  • Consider the below Thank You Page(view) where we need to create a link to email for “Sathiya”

thank-you-page

  • Select the word and click on Insert->Hyperlink under Links section

insert-hyperlink

  • In Insert Hyperlink dialog box, type the email address as mailto:sathiya@abc.com in address box and click ok
  • When you preview the form, you will see Sathiya as an hyperlink which upon clicking opens outlook with To address as Sathiya

linking-with-outlook

Thats it!!!

Isn’t it much simpler? We are going to follow the same step when we need to add someone to CC, BCC just by replacing the address. Well, many of you may know how to change the email address for adding CC, BCC, subject and body, let me put them below to see everything at a single page.

To create email link with To and CC:

  • Replace the address as mailto:Sathiya@abc.com?cc=Rai@xyz.com

To create email link with To, CC and BCC:

  • Replace the address as mailto:Sathiya@abc.com?cc=Rai@xyz.com&bcc=Ganga@abc.com

To create email link with To and Subject:

  • mailto:Sathiya@abc.com?Subject=Form related queries

To create email link with To, Subject, CC and BCC:

  • mailto:Sathiya@abc.com?Subject=Form related queries&cc=rai@xyz.com&bcc=ganga@pqr.com

To create email link with many persons in To & CC and with subject:

  • mailto:Sathiya@abc.com;Jhansi@abc.com;Varun@abc.com?Subject=Queries&cc=Rai@xyz.com;amit@xyz.com

To create an email link with To, Subject, CC, BCC and body:

  • mailto:Sathiya@abc.com;Jhansi@abc.com?Subject=Queries&cc=Rai@xyz.com&bcc=ganga@xyz.com&body=Could you please answer the below queries

To create an email link with multiple lines in body:

  • mailto:Sathiya@abc.com?Subject=Queries&body=Hi Team, %0A Could you please clarify the below queries.

where %0A is linefeed (new line).

 
If you found it useful, please like and rate this!!

Radio Button in Infopath browser forms


I heard many times my client saying that they need only radio buttons in infopath and not the drop down because when the fields are created in SharePoint site and customized using infopath, they are automatically converted in to drop down.

Are you too encountering the same problem? Don’t worry. Follow the below steps to convert it to radio button.

EXAMPLE:

To show you the steps, I have created a “Employee Info” list with below fields where Gender is selected as Radio button in choice type.

image001

If New item is to be added, the below form will be opened:

image002

This is the default form of SharePoint list. If you try to customize the look and feel of the list, using infopath, you will find that radio button is converted into drop down field as depicted below:

Gender

To make it as radio button, delete the field from the form view.

NOTE*: Do not delete the control permanently. Just delete it from the view.

In right corner of the infopath, you will see the list of fields with “Show advanced view” link. Click on the highlighted link. If you are not able to see the list of fields, click on the “DATA” menu -> Show Fields available under SharePoint Form Data section.

Fields.PNG

When you click on the field in advanced view, you will see a small inverted triangle. Click on the triangle and select Option button. Enter the number of choices to be inserted.

option button

image005

Type the labels for inserted radio buttons and edit the values in Properties. That is, right click on the radio button, select Properties and type the value in “Value when selected”.

properties.PNG

Alternative approach is to change the control to option button and perform a copy-paste for each choice. Finally, change the value of each choice as shown above in picture.

That’s it!!!

Make the form attractive and publish it.