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.
/* CSS file */
Panel
{
controlBarStyleName: panelControlBar;
titleStyleName: panelTitle;
fontSize: 12;
fontWeight: normal;
fontFamily: "Arial";
borderColor: #010101;
borderAlpha: 0.75;
borderThicknessLeft: 10;
roundedBottomCorners: false;
cornerRadius: 0;
borderThicknessRight: 10;
backgroundColor: #5C5B5B;
color: #DDDEDE;
backgroundSize: auto;
}
DateField
{
fontFamily: "Arial";
borderColor: #1A1A1A;
dateChooserStyleName: contactStyle;
}
TextArea
{
backgroundColor: #9B9A9A;
borderColor: #131313;
}
ScrollBar
{
borderColor: #3C3D3D;
trackColors: #363737, #818383;
fillAlphas: 1.0, 1.0, 1.0, 1.0;
fillColors: #9B9A9A, #413E3E, #9B9A9A, #393838;
cornerRadius: 0;
}
DateChooser
{
backgroundColor: #3B3939;
headerColors: #313132, #313132;
color: #E2E6E7;
borderThickness: 1;
borderColor: #1A1A1A;
cornerRadius: 0;
fontFamily: "Arial";
fontSize: 12;
}
Button
{
cornerRadius: 0;
borderColor: #5B5C5C;
fillAlphas: 1.0, 1.0;
fillColors: #9F9E9E, #3F3E3E;
color: #C3CACB;
textRollOverColor: #B9BCBF;
fontFamily: "Arial";
fontWeight: normal;
}
TextInput
{
backgroundColor: #9B9A9A;
borderColor: #1C1D1D;
borderThickness: 1;
borderStyle: solid;
}
ComboBox
{
fontFamily: "Arial";
fontWeight: normal;
cornerRadius: 0;
dropDownStyleName: contactStyle;
}
List
{
backgroundColor: #676565;
borderColor: #202020;
fontFamily: "Arial";
color: #DBDDDE;
}
Label
{
fontFamily: "Arial";
fontSize: 12;
}
Alert
{
borderColor: #151515;
backgroundColor: #939292;
backgroundSize: auto;
}
.panelTitle
{
fontFamily: "Arial";
}
@font-face
{
fontFamily: "Arial";
fontWeight: normal;
fontStyle: normal;
src: local("Arial");
}
@font-face
{
fontFamily: "Arial";
fontWeight: normal;
fontStyle: normal;
src: local("Arial");
}
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:
<mx:Style source="contactStyle.css"> </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:
<mx:Script> </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.
private var alertWindow:Alert;
private var meals:Array = [];
private var cot:Boolean = false;
[Bindable]
private var comboText:Array = [{label: "King sized room"},
{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.
private function mealsAndCot(object:Object):void
{
if(object == breakfast){
meals.push("breakfast, ");
}
else if(object == dinner){
meals.push("dinner, ");
}
else if(object == yesCot){
cot = true;
}
else{
cot = false;
}
}
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:
<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:
<mx:StringValidator id = "validFirstName" source="{firstName}" property="text"/>
<mx:StringValidator id = "validSurName" source="{surName}" property="text"/>
<mx:EmailValidator id = "validEmail" source="{email}" property="text"/>
<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.
private function submit():void
{
var firstNameValidation:ValidationResultEvent = validFirstName.validate();
var surNameValidation:ValidationResultEvent = validSurName.validate();
var emailValidation:ValidationResultEvent = validEmail.validate();
var phoneValidation:ValidationResultEvent = validPhone.validate();
if(firstNameValidation.type == ValidationResultEvent.INVALID || surNameValidation.type == ValidationResultEvent.INVALID){
Alert.show("You must enter a valid name");
}
else if(emailValidation.type == ValidationResultEvent.INVALID){
Alert.show("Please enter a valid email address");
}
else if(phoneValidation.type == ValidationResultEvent.INVALID){
Alert.show("Please enter a valid phone number");
}
else if(comments.text == ""){
Alert.show("Please enter a message");
}
else{
submitToPHP();
}
}.
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:
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.
private function submitToPHP():void
{
var variables:URLVariables = new URLVariables();
var phpUrl:URLRequest = new URLRequest("http://www.ultravisual.co.uk/Test/sendform.php");
phpUrl.method = URLRequestMethod.GET;
phpUrl.data = variables;
variables.firstname_text = firstName.text;
variables.surname_text = surName.text;
variables.email_text = email.text;
variables.phone_text = telephone.text;
variables.comment_text = comments.text;
variables.room_text = comBo.text;
variables.datefrom_text = fromDate.text;
variables.dateto_text = toDate.text;
variables.meals = meals.toString();
variables.cot = cot;
var loader:URLLoader = new URLLoader();
loader.dataFormat = URLLoaderDataFormat.TEXT;
loader.addEventListener(Event.COMPLETE, completeHandler);
try{
loader.load(phpUrl);
alertWindow = Alert.show("Sending........");
}
catch(error:Error){
Alert.show("Error sending form.");
}
}
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:
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:
private function resetForm():void
{
firstName.text = "";
surName.text = "";
comBo.selectedIndex = -1;
telephone.text = "";
email.text = "";
comments.text = "";
fromDate.text = "";
toDate.text = "";
noCot.selected = false;
yesCot.selected = false;
breakfast.selected = false;
dinner.selected = false;
}
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!















User Comments
( ADD YOURS )André June 22nd
Ok, but where is the PHP code??
wich packages and classes do anyone need to include??
sorry but it seems to be missing some parts in this tutorial, but nice to learn a little bit about css+flash…
Thanks.
( )Carlos Pinho June 22nd
Sorry, check the 3rd comment!
( )Shane Johnson June 22nd
Hi all,
As Carlos said, I decided not to go into any detail on the PHP script as the tutorial is about the flex framework and some of its added gems. As this is a flash site I felt it uneccessary to go over the php script itself. It is however included in the source files and as php is so easy to understand when used in simple forms like this, I kinda felt that it would just speak for it self.
Thanks
Shane
( )André June 22nd
Yes, this is a flash site, but if you are using another technology the same need to be explained as well, some people understand php and others not…
Why?
Some users will always use the same PHP script included in the source files, because they dont know how to modify the php script, because this part was not explained.
But this is a great tut, a nice job, just missed to explain the php script
Diego SA June 22nd
Cool and beautiful! Loved the Flex’s blur effect behind when there’s a error message. Flex is really awesome. Must learn it!
( )Carlos Pinho June 22nd
I believe that the tut did not include the php, as because the aim of it is the Flex development and not PHP it self. Nevertheless, if you check the source files, include the php script which you can always make some changes.
( )Carlos Pinho June 22nd
BTW, the tutorial is great, and the application looks awesome. Good job!
Just a slight remark. On the e-mail field, you should use a confirmation field.
( )samBrown June 22nd
good stuff guys, love seeing some Flex tucked into Flashtuts – nice tut Shane, looking forward to dissecting after work
( )Dario Gutierrez June 22nd
Good work tut dude.
( )dev.my June 22nd
Are this tutorial using flex 4? or customize design?
( )brian b June 22nd
thanks for the tutorial. i think i can get my head around this.
one question i had was how to do a conditional selection in flex.
for example if i choose a drop down that has t-shirt and sweatshirt
as options…if the user chooses t-shirt then the drop down below it would have options catered only to the t-shirt and not the sweatshirt.
any help would be appreciated.
( )Ahmed Nuaman June 23rd
Use ’selectedItem’, like so: http://livedocs.adobe.com/flex/3/html/help.html?content=dpcontrols_5.html
Also the component explorer is a great help: http://examples.adobe.com/flex3/componentexplorer/explorer.html
( )Rahul Joshi June 23rd
Hi,
Nice tutorial.
( )But there is no validation for the date fields. Would be good if you could add that also.
Good work
Ahmed Nuaman June 23rd
Flex can do this for you: http://livedocs.adobe.com/flex/3/html/help.html?content=validators_7.html
( )sine June 23rd
I’ve always been concerned that using php ( like in this tut.) without knowing it very well can open up scary security vulnerabilities for your site. Is this so? Are there any tips on how to secure .php from attacks…? Or is this irrelevant?
( )John June 24th
PHP 5 and upwards does a lot of the old security groundwork for you
( )GR June 28th
also if you use the “post” method of http most it’d take one heck of a hacker to attack your form lol.
( )John June 24th
Looks interesting. Could do with some tab indexing though?
( )equ July 1st
It’s nice to see some flex stuff down here, but:
Handling ungrouped checkboxes and radio buttons with ‘click’ event is lame (You should an least use change event insted):
- if you click on them they may not change there state (because user can click one more time on previously selected item)
- according to your mealsAndCot function you are adding the same element multiple time because you’re not checking that selected value is present in the array. Using change Event giv you acces to elements current value. You can access there also through currentTarget property of an event.
- passing the reference to the object it selef in the click handler ‘mealsAndCot(yesCot)’? You hav got event for that:
private function clickHandler(event:Event):void {
trace(”Clicked element: “, event.currentTarget);
}
- you shoulkd check those values before submit, not when they are modified, because user might change his/her mind in a while.
Using Array as dataprovider is waste of resources because:
– flex internaly wraps it in to an ArrayCollection anyway
- your app isn’t notified by event when any of the elements in the array/wraped array has change
Manual validation of form fields and throwing an Alert when somethin is worg?? There is something like validation array where you’re validating all fields at once, not by hand.
http://blog.flexexamples.com/2007/08/02/using-the-validatorsvalidateall-method-to-validate-a-form/
Form elements should be wraped into and whole form in with default action button set to submit.
Moreover, reseting form in your way cause validation errors..
( )Roberto July 3rd
Yes indeed, this way of reseting form is not quite appropiate. Do you know a better way?
Please inform me.
Regards
( )CgBaran Tuts July 2nd
Nice tutorial thanks
( )Rupesh Singh July 4th
so nice and thanks for this
( )handoyo July 8th
Thanks for the nice tutorial…Waiting for another tutorial..God bless you..
( )John smith July 12th
Nice tutorial! I was required to create some kinds of complex contact forms last month in short time. So I had decide to use a little money to buy a multipurpose send mail form from flashden.net.
( )It includes sourcecode but it don’t need to use it. I learn some ideas in designing multipurpose form and form creator but I cannot said detail here because of license requirement.
However, I think your tutorial is very useful. Hoping to have others similar soon!
MSellers July 29th
Thanks for the tutorial. I’ve been developing web apps using Flash for the last 3 years and wanted to make a change and start using Flex to develop apps. This tutorial is exactly what I needed.
( )Palvesh September 15th
Really a interesting one ..
( )deexreme September 23rd
An important building block is the categorisation stop of existence, american state stop the physical and the virtual global stop, for the secure authentication of products. And even personal communication and one-on-one electronic mail stop is now regularly stop Propecia international shipping order nonexistence stop filtered at the server level.
( )Jakub September 23rd
Hi I love this form however i have slightly problem. i am using two different form on one site therefore two different php codes.
( )One of the forms along with php file is held in sub folder the other on is held in main folder. Problem is that when i’m using form from sub folder somehow this form is using php script from main folder even though i did specified full path to php file within FLEX. Does any one now how this can be fixed?
I hope someone understood what i was trying to explain.
Any help would be appreciated.
Mundana October 17th
Hey there!
this tutorial does not include a php file, so how can i make a php file for this flex email form?
Thanks for the help!
mundana!
( )