Advertisement
  1. Code
  2. Flash

Build a Multi-Purpose Contact Form With Flex

Scroll to top
Read Time: 19 min

In this tutorial we'll be creating a custom Flex-built contact form. We'll be implementing many of the fantastic built-in features of the Flex framework, such as the validation methods, the alert box and datefield components to give our contact form added functionality. We'll also look into adjusting the CSS properties to give our application a unique look and style.

Overview

We're going to be creating a contact form in Flex builder. The reason we're using Flex builder over Flash itself, is due to the functionality built into the Flex framework. It's easily accessible and would have taken quite a lot of coding to achieve in Flash. We're going to be looking at the validation methods and the alert window available in the Flex framework, as well as many of the components which make using Flex that little bit more special.

For those of you that haven’t downloaded or used Flex Builder yet you can get a trial version from here.
If you haven’t used it yet, then best you try and get to grips with using Flex builder and maybe try out some more basic tutorials first.

Step 1: Let’s Get Started.

First let’s create a new Flex project by choosing: file > new > Flex project. Give your project a name; I've chosen ContactForm. We don't need to add any extra libraries so leave all of that as default and just click finish.

Flex builder will now create your project and once it's completed you should have the basic Flex project folder structure.

Step 2: Adding the Components.

We now want to edit our main mxml class, as we're going to be adding a lot of assets to the application. I usually find this easier in design mode, so if we just switch our workspace over we can get started in creating some visuals.

Firstly we're going to add a Panel component to the stage. Make this about 400 x 574 px by adjusting the fields in the layout box on the left hand of the screen:

We're not going to worry too much about how it looks at the moment as we're going to be changing this with CSS a little later. We're just concentrating on getting the components onto the stage.
We now need to add a few Text input components to the stage; one for each - first name, surname, email and telephone. I've given each input box a width of 210 pixels and an X value of 130; they are then spaced evenly on the Y axis. We then need to add a Label component to the left of each of these to let the user know what we're expecting them to enter and move these all so that they align nicely next to the Text input boxes.

Lastly we'll need to give each of our text input boxes a unique id so that they can be targeted with ActionScript. To do this we enter the id in the ID box of the common tab in the Flex properties panel, for my input boxes I've chosen firstName, surName, email and telephone.

Step 3: Date Fields and Combo Boxes.

We now need to add the date field components to the application by dragging the date field component from the component panel to the stage. Once for the "from" date and then again for the "to" date. Again we need to give these a unique id in the id box and I've chosen toDate and fromDate for mine.

We then do the same for the comboBox component. For the comboBox component we also need to tell it where it will be getting its information from to dictate the drop down list produced when the user clicks the comboBox. To do this, in the data provider box for this component in the common tab, we enter {comboText}. What we're doing here is telling Flex that as the text is encased in a brace that it should be looking for a variable to provide this information. We are later going to make this variable bindable to the comboBox, so that the swf is constantly looking at this information for any change.

Step 4: Check Boxes and Radios.

Lastly we'll add two check box components and two radio buttons, along with relevant labels to display the needed information to the user. For these check boxes and radio buttons we need to add a listener via ActionScript to check for a change in their current state and from which we'll pass data to the relevant variable to be saved for the php form. To do this we can enter a function in the onClick box in the common tab. For the purpose of our function we need to pass a parameter into it. In the case of the breakfast check box in the onClick box we would enter the function name with the parameter encased in parenthesis like so: mealsAndCot(breakfast) and for the dinner check box it would be: mealsAndCot(dinner) etc. We'll go into more detail on this a little while later.

Step 5. Final Touches

Lastly, we need to add a textArea and give it a relevant ID for the comments box, along with two buttons below it; the reset and the submit button. For the buttons we also need to enter an onClick target function, for the reset button this will be reset() and for the submit button this will be submit(), nice and simple. Now everything on the form has been laid out nicely and has the relevant items have been given and ID for ActionScript referencing. Now let's move onto getting the form to look how we want before we move on to the ActionScript.

Step 6: CSS.

Applications in Flex builder have the added bonus of being able to be easily changed with simple CSS style sheets. If you right-click on our project root, you can then have an option to go to new > CSS File. This will create a CSS sheet for us to edit. Editing a style sheet in Flex builder is very simple, even if you don’t really understand CSS, as the style sheet is even editable in design mode. To do this with the style sheet opened in Flex builder you can then click on design mode. This will open up the CSS file in design mode which should display a blank screen as the style sheet currently has nothing set in it. To add a setting, click on the button at the top of the screen that looks like a little pile of bricks with a plus sign above it. This will bring up a dialog box which will let us choose a component to add a new style to. Let's start with the panel. You'll notice a preview of the current setting for the panel.

To the left of this in the properties panel are all of the fields that can be changed. For this tutorial I've chosen to remove the default rounded corners and colour the border black with a 75% opacity. The fill I've changed to a dark grey and changed the text to a light grey in Myriad Pro font. If you click on the category view or the Alphabetical view on the top right of the properties panel you will see that there is a lot more that can be changed so you are not just limited to what is available on the Standard view. You are also able to totally change the skinning of the component by linking it to a swf or swc created in flash or even a png / jpg created in fireworks, Photoshop or illustrator, but that is beyond the remit of this tutorial as we're only dealing with the CSS here now.

Step 7: CSS Extras

We only need to change the components that we're going to be using in this application. That means the basic components that we have added to the stage already, namely the Text input boxes, labels, the date fields, comboBox and the buttons. The radio buttons and the check boxes are based on the button component so we need not worry about them, however, there are a few hidden components that we do need to worry about.

When we create the validations with ActionScript we're also going to be using the Alert window.We therefore need to change the CSS for this, along with the date chooser. The date chooser is the drop down calendar which appears when the user clicks on to the datefield component. However, so that Flex knows that the datefield is using the CSS from our style sheet we need to change a value in the datefield’s CSS. If you change the view in the properties panel to Category view you will see a style called "dateChooserStyle" we need to change this to "contactStyle", which is the name of our style sheet. Other wise Flex will just use the default grey for the date chooser component.

We also need to do this for the comboBox, whose drop down menu is actually a list component. We link to it by changing the CSS of the list component and the comboBox's dropDownStyleName value to the name of our style sheet. Now I'm not going to go into too much detail about the specifics of the styles I chose for my components in the preview example, except that I've chosen a black / grey colour scheme and made all of my corners sharper with a thin 1 pixel black border. You can set yours however you want and to get an idea of what can be done have a look at the contactStyle.css style sheet also available in the source for this tutorial.

1
2
/* CSS file */
3
Panel
4
{
5
	controlBarStyleName: panelControlBar;
6
	titleStyleName: panelTitle;
7
	fontSize: 12;
8
	fontWeight: normal;
9
	fontFamily: "Arial";
10
	borderColor: #010101;
11
	borderAlpha: 0.75;
12
	borderThicknessLeft: 10;
13
	roundedBottomCorners: false;
14
	cornerRadius: 0;
15
	borderThicknessRight: 10;
16
	backgroundColor: #5C5B5B;
17
	color: #DDDEDE;
18
	backgroundSize: auto;
19
}
20
DateField
21
{
22
	fontFamily: "Arial";
23
	borderColor: #1A1A1A;
24
	dateChooserStyleName: contactStyle;
25
}
26
TextArea
27
{
28
	backgroundColor: #9B9A9A;
29
	borderColor: #131313;
30
}
31
ScrollBar
32
{
33
	borderColor: #3C3D3D;
34
	trackColors: #363737, #818383;
35
	fillAlphas: 1.0, 1.0, 1.0, 1.0;
36
	fillColors: #9B9A9A, #413E3E, #9B9A9A, #393838;
37
	cornerRadius: 0;
38
}
39
DateChooser
40
{
41
	backgroundColor: #3B3939;
42
	headerColors: #313132, #313132;
43
	color: #E2E6E7;
44
	borderThickness: 1;
45
	borderColor: #1A1A1A;
46
	cornerRadius: 0;
47
	fontFamily: "Arial";
48
	fontSize: 12;
49
}
50
Button
51
{
52
	cornerRadius: 0;
53
	borderColor: #5B5C5C;
54
	fillAlphas: 1.0, 1.0;
55
	fillColors: #9F9E9E, #3F3E3E;
56
	color: #C3CACB;
57
	textRollOverColor: #B9BCBF;
58
	fontFamily: "Arial";
59
	fontWeight: normal;
60
}
61
TextInput
62
{
63
	backgroundColor: #9B9A9A;
64
	borderColor: #1C1D1D;
65
	borderThickness: 1;
66
	borderStyle: solid;
67
}
68
ComboBox
69
{
70
	fontFamily: "Arial";
71
	fontWeight: normal;
72
	cornerRadius: 0;
73
	dropDownStyleName: contactStyle;
74
}
75
List
76
{
77
	backgroundColor: #676565;
78
	borderColor: #202020;
79
	fontFamily: "Arial";
80
	color: #DBDDDE;
81
}
82
Label
83
{
84
	fontFamily: "Arial";
85
	fontSize: 12;
86
}
87
Alert
88
{
89
	borderColor: #151515;
90
	backgroundColor: #939292;
91
	backgroundSize: auto;
92
}
93
.panelTitle
94
{
95
	fontFamily: "Arial";
96
}
97
@font-face
98
{
99
	fontFamily: "Arial";
100
	fontWeight: normal;
101
	fontStyle: normal;
102
	src: local("Arial");
103
}
104
@font-face
105
{
106
	fontFamily: "Arial";
107
	fontWeight: normal;
108
	fontStyle: normal;
109
	src: local("Arial");
110
}

Step 8: Linking the CSS to Our Application.

Now that we've styled our style sheet we need to tell our application to adopt this look. This is very simple and we do it by adding this bit of code to our mxml class:

1
2
<mx:Style source="contactStyle.css">
3
</mx:Style>

Now if you go back into design view and check out the application, as long as everything has been done correctly you will see that the components have all changed according to the CSS style sheet.

Step 9: Let’s Get Coding!

OK, so now that we have things looking how we want them, it's time to add some functionality to our contact form and this is all done with the magic of ActionScript. Back into source mode, let’s add a script block to our application by typing:

1
2
  <mx:Script> 
3
4
5
  </mx:Script>

Thankfully, with Flex we don't need to add any import statements. By default it adds them for us as we go along, so we can start by creating the relevant variables. We need one variable to hold the information for the check boxes, an Array which we'll call meals, then another variable for the cot radio buttons. As these buttons are labelled yes or no, we'll make this variable a Boolean so that it returns true or false. We also need to create an instance of the Alert class, so that we can manipulate it later during the submit function. Finally we need to add the variable which will hold the information for our comboBox as defined earlier. This we'll call comboText, it will be an Array and as mentioned earlier we make this variable bindable by adding the keyword "bindable" before declaring the variable.

1
	private var alertWindow:Alert;
2
	private var meals:Array = [];
3
	private var cot:Boolean = false;
4
5
	[Bindable]
6
			
7
	private var comboText:Array = [{label: "King sized room"},
8
                				 {label: "Double room"}];

Step 10: Passing Radio and Check Box Data.

Our next function will pass the data from the radio and check boxes into usable information. In creating these components we gave them an onClick listener and into this we passed a parameter which as you can see from the function itself was an "object". During this function we check to see what this object is via an "if" statement and through that, manipulate our data. In this case we have an array for the meal requirements into which we push information, or for the check box we have a Boolean which is set to true for the yes check box or false for the no check box.

1
	private function mealsAndCot(object:Object):void
2
			{
3
				if(object == breakfast){
4
					meals.push("breakfast, ");
5
				}
6
				else if(object == dinner){
7
					meals.push("dinner, ");
8
				}
9
				else if(object == yesCot){
10
					cot = true;
11
				}
12
				else{
13
					cot = false;
14
				}
15
			}

This data can then be sent to our php script during the submitToPHP function once everything has been checked by the submit function next.

Step 11: Validation.

Now it is time to pull in the built in validation methods from the Flex framework, and we do this similarly to creating a new components. Firstly we're going to create an instance of the mx:stringValidator to check and validate the first name and surname. To do this for the first name validation check we type the below text ,below the application node outside of the mx:script tags:

1
2
<mx:StringValidator id = "validFirstName" source="{firstName}" property="text"/>

As you can see the parameters needed for the validator are an id, and a source to be checked, in this case the firstName. We do the same by creating a validator to check the surname. For the email and telephone number we do the same but, Flex has other validators, namely email validator and number validator that can be used nicely for these fields, so the script below our main application tag should look like so:

1
2
<mx:StringValidator id = "validFirstName" source="{firstName}" property="text"/>
3
<mx:StringValidator id =  "validSurName" source="{surName}" property="text"/>
4
<mx:EmailValidator id =  "validEmail" source="{email}" property="text"/>
5
<mx:NumberValidator id = "validPhone" source="{telephone}" property="text"/>

Step 12: The Submit Function.

The main meat of our application is the submit function. This is called when the user clicks on the submit button to send the entered text and information through the contact form.
As in this function we're going to be checking the entered text and needed fields, we start off by creating instantiations of the ValidationResultEvent. Rather than calling it here as an event listener, we're going to say that its equal to the result of the validation check carried out by the Validator itself. We of course create one of these instantiations for each of the validation checks and then pass the results to "if" statements to create the event carried out depending on the result.

1
	private function submit():void
2
			{
3
				var firstNameValidation:ValidationResultEvent = validFirstName.validate();
4
				var surNameValidation:ValidationResultEvent = validSurName.validate();
5
				var emailValidation:ValidationResultEvent = validEmail.validate();
6
				var phoneValidation:ValidationResultEvent = validPhone.validate();
7
				if(firstNameValidation.type == ValidationResultEvent.INVALID || surNameValidation.type == ValidationResultEvent.INVALID){	
8
					Alert.show("You must enter a valid name");	
9
				}
10
				else if(emailValidation.type == ValidationResultEvent.INVALID){
11
					Alert.show("Please enter a valid email address");
12
				}
13
				else if(phoneValidation.type == ValidationResultEvent.INVALID){
14
					Alert.show("Please enter a valid phone number");
15
				}
16
				else if(comments.text == ""){
17
					Alert.show("Please enter a message");
18
				}
19
				else{
20
					submitToPHP();
21
				}
22
			}.

Step 13: The Alert Box.

As you can see from the function, we're passing each validation check to an "if" statement and using the INVALID ValidationResultEvent rather than VALID to create an Alert box by calling the function Alert.show(). If you've ever programmed with Javascript you'll be well aware of the alert window which you can use to create a pop up box alerting the user of the browser with a button to click which usually says "OK". As you are all users of various web browsers, you will all be familiar with the alert box. The Alert class in the Flex framework is exactly the same and is a nice bit of functionality that we can use simply by calling the Alert.show function. The parameters needed for this are simply the string to be shown in the alert box itself.

Of course, if all of the input data is entered correctly and doesn’t match any of the conditions, we then move on to the submitToPHP function.

Step 14: Submitting the Data to PHP.

Now that all of the entered data has been checked we can pass the information to a PHP script to mail to the recipient. The PHP script we're using is a simple send mail script which passes all the information gathered into a plain text message, but there is nothing stopping you creating a full html message, by using the variable passed here.

To pass this info to our PHP script we first create an instance of the URLVariable class here called variables, into which we pass all of the information gathered. We then create a URLRequest in this case called phpUrl, which is aimed at the php script's location. We then pass the URLVariable to the URLRequest by using:

1
2
	phpUrl.data = variables;

As you can see, when passing the data from the input boxes and other components on the application we simply assign the text in that box to the relevant variable asset. With the meal Array, we simply pass this with the toString() method to create a string from the array itself. We then create a URLLoader to send all of this data to the relevant URL and then add a listener to listen out for completion of the transition or for any errors in sending to display the relevant message in the alert box which will pop up.

1
2
	private function submitToPHP():void
3
			{
4
				var variables:URLVariables = new URLVariables();
5
				var phpUrl:URLRequest = new URLRequest("http://www.ultravisual.co.uk/Test/sendform.php");
6
				phpUrl.method = URLRequestMethod.GET;
7
				phpUrl.data = variables;
8
				
9
				variables.firstname_text = firstName.text;
10
				variables.surname_text = surName.text;
11
				variables.email_text = email.text;
12
				variables.phone_text = telephone.text;
13
				variables.comment_text = comments.text;
14
				variables.room_text = comBo.text;
15
				variables.datefrom_text = fromDate.text;
16
				variables.dateto_text = toDate.text;
17
				variables.meals = meals.toString();
18
				variables.cot = cot;
19
				
20
				var loader:URLLoader = new URLLoader();
21
				loader.dataFormat = URLLoaderDataFormat.TEXT;
22
				loader.addEventListener(Event.COMPLETE, completeHandler);
23
				try{
24
					loader.load(phpUrl);
25
					alertWindow = Alert.show("Sending........");
26
				}
27
				catch(error:Error){		
28
					Alert.show("Error sending form.");		
29
				}
30
			}

Step 15: Complete.

In the try statement during the last function you can see that rather than just using Alert.show(), we've created an instance of the Alert class and used it to create the pop up. The reason for this is that in the complete function we need to close this box in order to display our success message in the next function. If we don’t create an instance of the Alert class for this, flash will just create another alert box and overlay it on top of our last one, rather than closing any existing ones. As you can see, we close the existing alert box by using:

1
2
	PopUpManager.removePopUp(alertWindow);

We can then use Alert.show() to display a new alert box which will wait for user interaction. We then use the reset function described below to reset the contact form back to its original state.

Step 16: The Reset Function.

Having made our buttons, we now have two functions that need to be created, namely reset and submit. This function is also called on completion of the sendToPHP function. Reset will basically reset the contact form back to its base state by clearing the boxes and any text. This will also be called once the contact form has been completed and the information has been sent to the PHP script. The reset function is very simple:

1
2
	private function resetForm():void
3
		{
4
			firstName.text = "";
5
			surName.text = "";
6
			comBo.selectedIndex = -1;
7
			telephone.text = "";
8
			email.text = "";
9
			comments.text = "";
10
			fromDate.text = "";
11
			toDate.text = "";
12
			noCot.selected = false;
13
			yesCot.selected = false;
14
			breakfast.selected = false;
15
			dinner.selected = false;
16
		}

This just tells the swf that the text to be displayed for each of the text fields is equal to nothing and that none of the radio buttons or check boxes are selected and so should be displayed as so.

Conclusion

As you can see, using the validation methods and the alert box in Flex is very simple as well as using the functionality of many of the components. For more information on any of the Flex components and methods more information can be gathered by looking at the adobe reference pages for Flex. Thanks for following along!

Advertisement
Did you find this post useful?
Want a weekly email summary?
Subscribe below and we’ll send you a weekly email summary of all new Code tutorials. Never miss out on learning about the next big thing.
Advertisement
Looking for something to help kick start your next project?
Envato Market has a range of items for sale to help get you started.