<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Anaara - Vision to Reality &#187; Flex</title>
	<atom:link href="http://blog.anaara.com/archives/category/flex/feed" rel="self" type="application/rss+xml" />
	<link>http://blog.anaara.com</link>
	<description>Flex, Flash, Rich Internet Applications (RIA&#039;s), and Post Production for Film and Video</description>
	<lastBuildDate>Fri, 02 Sep 2011 16:03:21 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<item>
		<title>Customizing the Login Box – Part 4 – Preventing Duplicate Records with FB4, PHP and mySQL</title>
		<link>http://blog.anaara.com/archives/403</link>
		<comments>http://blog.anaara.com/archives/403#comments</comments>
		<pubDate>Mon, 14 Mar 2011 15:47:13 +0000</pubDate>
		<dc:creator>Dan Orlando</dc:creator>
				<category><![CDATA[ActionScript]]></category>
		<category><![CDATA[Adobe]]></category>
		<category><![CDATA[Flash]]></category>
		<category><![CDATA[Flex]]></category>
		<category><![CDATA[Flex 4]]></category>
		<category><![CDATA[RIA]]></category>

		<guid isPermaLink="false">http://blog.anaara.com/?p=403</guid>
		<description><![CDATA[In this part of the series, we&#8217;re not so much focusing on the login part of the component we&#8217;ve been building, but rather the registration form. More specifically, we want to check the database prior to adding a new user &#8230; <a href="http://blog.anaara.com/archives/403">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>In this part of the series, we&#8217;re not so much focusing on the login part of the component we&#8217;ve been building, but rather the registration form. More specifically, we want to check the database prior to adding a new user record to make sure we&#8217;re not about to get a duplicate user record in the database. This is going to utilize a combination of PHP and Flex. When the user clicks the &#8220;Save&#8221; button from the registration form, it will send both the username and email address to PHP, which will run a query against the database. PHP will then send back a &#8220;true&#8221; or &#8220;false&#8221; response based on whether the username and/or email address already exists. Once Flex receives the answer, it will then either allow registration to continue with adding the record, or it will send an Alert notifying the user that there is a problem with either the username or email address or both.</p>
<p>Lets start by adding the needed PHP file.</p>
<p>duplicates.php</p>
<pre>&lt;?php

$host="localhost"; // Host name

  $username="root"; // Mysql username

  $password="root"; // Mysql password

  $db_name="example12"; // Database name

//Connect to server and select databse.

  mysql_connect("$host", "$username", "$password")or die("cannot connect to server");

  mysql_select_db("$db_name")or die("cannot select DB");

// table name

  $tbl_name=users;

//assign the data passed from Flex to variables

  $username = mysql_real_escape_string($_POST["usernameTextInput2"]);

  $email = mysql_real_escape_string($_POST["emailTextInput2"]);

//check if email id is already present

  $chk1=mysql_query("Select * FROM $tbl_name WHERE email='$email'");

  $num1=mysql_num_rows($chk1);

$dupemail .= "&lt;dupemailchk&gt;";

  if($num1 &gt; 0)

  {

  $dupemail .= "true";

  }

  else

  {

  $dupemail .= "false";

  }

  $dupemail .= "&lt;/dupemailchk&gt;";

//check if email id is already present

  $chk2=mysql_query("Select * FROM $tbl_name WHERE username='$username'");

  $num2=mysql_num_rows($chk2);

$dupuser .= "&lt;dupusernamechk&gt;";

  if($num2 &gt; 0)

  {

  $dupuser .= "true";

  }

  else

  {

  $dupuser .= "false";

  }

  $dupuser .= "&lt;/dupusernamechk&gt;";

//output the XML

  print ($dupemail);

  print ($dupuser);

?&gt;</pre>
<p>What this is saying is: Take the user&#8217;s desired username (&#8220;usernameTextInput2&#8243;) and email address (&#8220;emailTextInput2&#8243;)  and check against the database&#8217;s users table to see if there is a match in the respective column. If there is, send back true, otherwise send back false. There will be two separate answers returned, one for username and one for email address. This allows the application to know which Alert to give the user.</p>
<p><strong>Creating the Function</strong></p>
<p>This function first checks to see  if there is a duplicate username, and if there is a duplicate email address, and if there is not for either of them, it will call <code>saveBtn_clickHandler</code>.</p>
<pre>private function dupCheck(event:ResultEvent):void

  {

  if(event.result.dupusernamechk == true)

  { 

  mx.controls.Alert.show('Please choose another username, this one is already taken.');

  }

  else if(event.result.dupemailchk == true)

  { 

  mx.controls.Alert.show('This email address has already been registered.');

  }

  else

  {

  saveBtn_clickHandler();

  }

  }</pre>
<p><strong>Creating the Service Call</strong></p>
<pre>&lt;mx:HTTPService id="duplicate_check" result="dupCheck(event)" showBusyCursor="true" method="POST" url="duplicates.php" useProxy="false"&gt;

  &lt;mx:request xmlns=""&gt;

  &lt;usernameTextInput2&gt;

  {usernameTextInput2.text}

  &lt;/usernameTextInput2&gt;

  &lt;emailTextInput2&gt;

  {emailTextInput2.text}

  &lt;/emailTextInput2&gt;

  &lt;/mx:request&gt;

  &lt;/mx:HTTPService&gt;</pre>
<p>The above code is telling PHP the names of the variables that we are sending over and telling Flex where to get that information, what function we are calling, how we are communicating with PHP, and where the file is located.</p>
<p>Component Changes</p>
<p>First we need to make sure that we are calling <code>duplicate_check</code> HTTPService rather than <code>saveBtn_clickHandler</code>. This allows us to check for duplicates, and then if there are none, then the <code>dupCheck</code> function will call<code>saveBtn_clickHandler</code>.</p>
<p>Change From:</p>
<p><code> </code></p>
<p><code>&lt;s:Button x="10" y="118" label="Save" id="saveBtn" click="saveBtn_clickHandler(event)" enabled="false" includeIn="register"/&gt;</code></p>
<p><code> </code></p>
<p>.</p>
<p>Change To:</p>
<p><code> </code></p>
<p><code>&lt;s:Button x="10" y="118" label="Save" id="saveBtn" click="duplicate_check.send()" enabled="false" includeIn="register"/&gt;</code></p>
<p><code> </code></p>
<p>Secondly, we need to remove the argument being passed by saveBtn_clickHandler which was created automatically for us by FB4.</p>
<p>Change From:</p>
<p><code> </code></p>
<p><code>protected function saveBtn_clickHandler(event:MouseEvent):void</code></p>
<p><code> </code></p>
<p>Change To:</p>
<p><code> </code></p>
<p><code>protected function saveBtn_clickHandler():void</code></p>
<p><code> </code></p>
<p>That&#8217;s it. Go ahead and run the application and try to create a duplicate entry. You will find that you will be alerted when doing so.</p>
<p><a href="http://blog.anaara.com/wp-content/uploads/2011/02/CLB6-1.gif"><img class="alignleft size-full wp-image-404" src="http://blog.anaara.com/wp-content/uploads/2011/02/CLB6-1.gif" alt="Flex 4 - Preventing Duplicate Users in Database - FB4, PHP, mySQL" width="291" height="200" /></a></p>
<p>Application should now look like:</p>
<pre>&lt;?xml version="1.0" encoding="utf-8"?&gt;

  &lt;s:Application xmlns:fx="http://ns.adobe.com/mxml/2009" 

  xmlns:s="library://ns.adobe.com/flex/spark" 

  xmlns:mx="library://ns.adobe.com/flex/mx"

  applicationComplete="init()"

  minWidth="955" minHeight="600" xmlns:valueObjects="valueObjects.*"

  xmlns:usersservice="services.usersservice.*"&gt;

  &lt;fx:Script&gt;

  &lt;![CDATA[

  import mx.controls.Alert;

  import mx.events.ValidationResultEvent;

  import mx.rpc.events.ResultEvent;

  import mx.validators.EmailValidator;

  import mx.validators.StringValidator;

  import spark.events.TextOperationEvent;

  private var userid:int;

  private var usertype:String;

  private var usernameVal:StringValidator = new StringValidator();

  private var passwordVal:StringValidator = new StringValidator();

  private var emailVal:EmailValidator = new EmailValidator();

  private var usernameVal2:StringValidator = new StringValidator();

  private var emailVal2:EmailValidator = new EmailValidator();

  private var passwordVal2:StringValidator = new StringValidator();

  [Bindable]

  private var cookieAction:Boolean;

  protected function saveBtn_clickHandler():void

  {

  var users2:Users = new Users();

  users2.username = usernameTextInput2.text;

  users2.email = emailTextInput2.text;

  users2.password = passwordTextInput2.text;

  users2.user_type = "user";

  createUsersResult.token = usersService.createUsers(users2);

  createUsersResult.token = usersService.commit();

  currentState = 'loggedOut'; 

  }

  private function checkLogin(event:ResultEvent):void

  {

  userid = event.result.loginsuccess;

  trace (userid);

  usertype = event.result.usertype;

  trace (usertype);

  cookieAction = event.result.usertype;

  trace (cookieAction);

  if (userid != 0)

  {

  currentState = usertype;

  }

  else

  {

  mx.controls.Alert.show('Invalid username/password');

  }

  }

  protected function createUsersResult_resultHandler(event:ResultEvent):void

  {

  mx.controls.Alert.show('Thank you for registering. You may login now!');

  currentState = "loggedOut";

  }

  private function init():void

  {

  getCookie.send();

  }

 protected function getCookie_resultHandler(event:ResultEvent):void

  {

  if(event.result.storedCookie == true)

  {

  cookieAction = true;

  username.text = event.result.creds.username;

  password.text = event.result.creds.password;

  loginBtn.enabled = true;

  }

  else

  {

  cookieAction == false;

  }

  }

  private function getPassword(event:ResultEvent):void

  {

  if(event.result.getPassword == "yes")

  {

  mx.controls.Alert.show('Your password has been emailed to you.');

  currentState = "loggedOut";

  }

  else

  {

  mx.controls.Alert.show('Invalid email, please try again.');

  } 

  }

 protected function loggedOutVal_changeHandler(event:TextOperationEvent):void

  {

  if (username.text)

  {

  var valUsername:ValidationResultEvent;

  usernameVal.source = username;

  usernameVal.property = "text";

  usernameVal.minLength=6;

  }

  if (password.text)

  {

  var valPassword:ValidationResultEvent;

  passwordVal.source = password;

  passwordVal.property = "text";

  passwordVal.minLength=6;

  }

  valUsername = usernameVal.validate();

  valPassword = passwordVal.validate();

  if(valUsername.type == "valid" &amp;&amp; valPassword.type == "valid")

  loginBtn.enabled = true;

  else

  loginBtn.enabled = false;

  }

 protected function email_toVal_changeHandler(event:TextOperationEvent):void

  { 

  if (email_to.text)

  {

  var valEmail:ValidationResultEvent;

  emailVal.source = email_to;

  emailVal.property = "text";

  }

  valEmail = emailVal.validate();

  if(valEmail.type == "valid")

  emailBtn.enabled = true;

  else

  emailBtn.enabled = false;

  }

 protected function registerVal_changeHandler(event:TextOperationEvent):void

  {

  if (usernameTextInput2.text)

  {

  var valUsername2:ValidationResultEvent;

  usernameVal2.source = usernameTextInput2;

  usernameVal2.property = "text";

  usernameVal2.minLength=6;

  }

  if (emailTextInput2.text)

  {

  var valEmail2:ValidationResultEvent;

  emailVal2.source = emailTextInput2;

  emailVal2.property = "text";

  }

  if (passwordTextInput2.text)

  {

  var valPassword2:ValidationResultEvent;

  passwordVal2.source = passwordTextInput2;

  passwordVal2.property = "text";

  passwordVal2.minLength=6;

  }

  valUsername2 = usernameVal2.validate();

  valEmail2 = emailVal2.validate();

  valPassword2 = passwordVal2.validate();

  if(valUsername2.type == "valid" &amp;&amp; valPassword2.type == "valid" &amp;&amp; valEmail2.type == "valid")

  saveBtn.enabled = true;

  else

  saveBtn.enabled = false;

  }

  private function dupCheck(event:ResultEvent):void

  {

  if(event.result.dupusernamechk == true) 

  { 

  mx.controls.Alert.show('Please choose another username, this one is already taken.'); 

  }

  else if(event.result.dupemailchk == true) 

  { 

  mx.controls.Alert.show('This email address has already been registered.'); 

  }

  else

  {

  saveBtn_clickHandler();

  }

  }

 ]]&gt;

  &lt;/fx:Script&gt;

  &lt;s:states&gt;

  &lt;s:State name="loggedOut"/&gt;

  &lt;s:State name="forgotPW"/&gt;

  &lt;s:State name="register"/&gt;

  &lt;s:State name="user"/&gt;

  &lt;s:State name="admin"/&gt;

  &lt;/s:states&gt;

  &lt;fx:Declarations&gt;

  &lt;s:HTTPService id="login_user" result="checkLogin(event)" showBusyCursor="true" method="POST"

  url="login.php" useProxy="false"&gt;

  &lt;s:request xmlns=""&gt;

  &lt;username&gt;

  {username.text}

  &lt;/username&gt;

  &lt;password&gt;

  {password.text}

  &lt;/password&gt;

  &lt;logincookie&gt;

  {setCookie.selected}

  &lt;/logincookie&gt;

  &lt;/s:request&gt;

  &lt;/s:HTTPService&gt;

  &lt;s:HTTPService id="getCookie" result="getCookie_resultHandler(event)" method="POST" url="getCookie.php"/&gt;

  &lt;mx:HTTPService id="get_password" result="getPassword(event)" showBusyCursor="true" method="POST"

  url="forgotPW.php" useProxy="false"&gt;

  &lt;mx:request xmlns=""&gt;

  &lt;email_to&gt;

  {email_to.text}

  &lt;/email_to&gt;

  &lt;/mx:request&gt;

  &lt;/mx:HTTPService&gt;

  &lt;mx:HTTPService id="duplicate_check" result="dupCheck(event)" showBusyCursor="true" method="POST"

  url="duplicates.php" useProxy="false"&gt;

  &lt;mx:request xmlns=""&gt;

  &lt;usernameTextInput2&gt;

  {usernameTextInput2.text}

  &lt;/usernameTextInput2&gt;

  &lt;emailTextInput2&gt;

  {emailTextInput2.text}

  &lt;/emailTextInput2&gt;

  &lt;/mx:request&gt;

  &lt;/mx:HTTPService&gt;

  &lt;valueObjects:Users id="users"/&gt;

  &lt;usersservice:UsersService id="usersService" fault="Alert.show(event.fault.faultString + '\n' + event.fault.faultDetail)" showBusyCursor="true"/&gt;

  &lt;s:CallResponder id="createUsersResult" result="createUsersResult_resultHandler(event)"/&gt;

  &lt;!-- Place non-visual elements (e.g., services, value objects) here --&gt;

  &lt;/fx:Declarations&gt;

  &lt;s:Panel width="250" height="200" title="Flex 4 Login Box" horizontalCenter="0" verticalCenter="0"&gt;

  &lt;s:Label x="10" y="18" text="Username" includeIn="loggedOut"/&gt;

  &lt;s:TextInput x="110" y="10" id="username" change="loggedOutVal_changeHandler(event)" includeIn="loggedOut"/&gt;

  &lt;s:Label x="12" y="47" text="Password" includeIn="loggedOut"/&gt;

  &lt;s:TextInput x="110" y="40" id="password" change="loggedOutVal_changeHandler(event)" displayAsPassword="true" includeIn="loggedOut"/&gt;

  &lt;s:Button x="10" y="72" id="loginBtn" label="Login" click="login_user.send();" enabled="false" includeIn="loggedOut"/&gt;

  &lt;s:Button x="120" y="72" label="Forgot Login Info?" click="currentState='forgotPW'" includeIn="loggedOut"/&gt;

  &lt;s:CheckBox x="10" y="101" label="Remember Me" id="setCookie" selected="{cookieAction}" includeIn="loggedOut"/&gt;

  &lt;s:Label x="195" y="103" text="Sign Up" click="currentState='register'" includeIn="loggedOut"/&gt;

  &lt;s:Label x="10" y="46" text="Email:" includeIn="forgotPW"/&gt;

  &lt;s:TextInput x="110" y="39" id="email_to" change="email_toVal_changeHandler(event)" includeIn="forgotPW"/&gt;

  &lt;s:Button x="8" y="72" id="emailBtn" label="Get Login Info" click="get_password.send();" enabled="false" includeIn="forgotPW"/&gt;

  &lt;s:Button x="168" y="72" label="&amp;lt;&amp;lt; Login" click="currentState='loggedOut'" includeIn="forgotPW"/&gt;

  &lt;s:Label x="10" y="31" text="Username:" includeIn="register"/&gt;

  &lt;s:TextInput x="110" y="24" id="usernameTextInput2" text="{users.username}" change="registerVal_changeHandler(event)" includeIn="register"/&gt;

  &lt;s:Label x="10" y="61" text="Email:" includeIn="register"/&gt;

  &lt;s:TextInput x="110" y="54" id="emailTextInput2" text="{users.email}" change="registerVal_changeHandler(event)" includeIn="register"/&gt;

  &lt;s:Label x="10" y="91" text="Password:" includeIn="register"/&gt;

  &lt;s:TextInput x="110" y="84" id="passwordTextInput2" text="{users.password}" change="registerVal_changeHandler(event)" displayAsPassword="true" includeIn="register"/&gt;

  &lt;s:Button x="10" y="118" label="Save" id="saveBtn" click="duplicate_check.send()" enabled="false" includeIn="register"/&gt;

  &lt;s:Button x="168" y="118" label="&amp;lt;&amp;lt; click="currentState='loggedOut'" Login" includeIn="register"/&gt;

  &lt;s:Label x="10" y="10" text="Welcome User" includeIn="user"/&gt;

  &lt;s:Button x="10" y="30" label="Log Out" click="currentState='loggedOut'" includeIn="user"/&gt;

  &lt;s:Label x="10" y="10" text="Welcome Admin" includeIn="admin"/&gt;

  &lt;s:Button x="10" y="30" label="Admin Log Out" click="currentState='loggedOut'" includeIn="admin"/&gt;

  &lt;/s:Panel&gt;

  &lt;/s:Application&gt;</pre>
]]></content:encoded>
			<wfw:commentRss>http://blog.anaara.com/archives/403/feed</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Customizing the Login Box – Part 3 – Validation with FB4, PHP and MySql</title>
		<link>http://blog.anaara.com/archives/399</link>
		<comments>http://blog.anaara.com/archives/399#comments</comments>
		<pubDate>Mon, 07 Mar 2011 20:02:00 +0000</pubDate>
		<dc:creator>Dan Orlando</dc:creator>
				<category><![CDATA[ActionScript]]></category>
		<category><![CDATA[Adobe]]></category>
		<category><![CDATA[Flash]]></category>
		<category><![CDATA[Flex]]></category>
		<category><![CDATA[Flex 4]]></category>
		<category><![CDATA[mySQL]]></category>
		<category><![CDATA[php]]></category>
		<category><![CDATA[RIA]]></category>

		<guid isPermaLink="false">http://blog.anaara.com/?p=399</guid>
		<description><![CDATA[In this tutorial we will continue with the Login Box that we have been building in the last several tutorials. In this tutorial we are going to cover how to validate using a string validator and email validator. There are &#8230; <a href="http://blog.anaara.com/archives/399">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>In this tutorial we will continue with the Login Box that we have been building in the last several tutorials. In this tutorial we are going to cover how to validate using a string validator and email validator. There are a number of validators available as well, but once you have the basic concept down, you will be able to implement the others without a hitch.</p>
<p><strong>Lets Get Started</strong></p>
<p>The first thing you need to do is figure out what fields you want to validate. In our case, we have six, as follows:</p>
<p>1. Username &lt;loggedOut&gt;</p>
<p>2. Password &lt;loggedOut&gt;</p>
<p>3. Email &lt;forgotPW&gt;</p>
<p>4. Username &lt;register&gt;</p>
<p>5. Email &lt;register&gt;</p>
<p>6. Password &lt;register&gt;</p>
<p>The second thing that you need to do is figure out if there are going to be any buttons that should be disabled/enabled based on TextInput field validation. In our case, the answer is yes:</p>
<p>1. Login &lt;loggedOut&gt;</p>
<p>2. Get Login Info &lt;forgotPW&gt;</p>
<p>3. Save &lt;register&gt;</p>
<p>Also, we need to note that we want the button in each state to be disabled until ALL textInput fields in the respective state pass validation.</p>
<p>Now that we have outlined our goals, you need to think about the validation rules, or what constitutes each field being considered valid.  For the Username and Password fields, we just want to make sure that they are over six (6) characters long, and for the email address, we want to make sure that the properties of the string match that of a properly formed email address.</p>
<p>Importing the Necessary Classes</p>
<pre>import mx.events.ValidationResultEvent;
  import mx.rpc.events.ResultEvent;
  import mx.validators.EmailValidator;
  import mx.validators.StringValidator;</pre>
<p><strong>Creating Variables</strong></p>
<pre>private var usernameVal:StringValidator = new StringValidator();
  private var passwordVal:StringValidator = new StringValidator();

private var emailVal:EmailValidator = new EmailValidator();

private var emailVal2:EmailValidator = new EmailValidator();
  private var usernameVal2:StringValidator = new StringValidator();
  private var passwordVal2:StringValidator = new StringValidator();</pre>
<p>Now that the variables have been created and the classes have been imported, we need to follow a series of steps for each state.</p>
<p>1. Write the Validation Function</p>
<p>2. Set the default state of the respective button to disabled</p>
<p>3. Decide when and how you want to call the function</p>
<p><strong>loggedOut State Validation</strong></p>
<p>In this state you have the username and password TextInput fields to validate. These two fields are only being validated to ensure that they have over 6 characters each. We will start by making the necessary changes to the loggedOut state to prepare it.</p>
<p>Step 1. Changes to State Components</p>
<p>Here, we are going to add the change event on each of the text boxes, add an id and enabled properties to the &#8220;Login&#8221; button.</p>
<p>Change From:</p>
<p><code> </code></p>
<p><code>&lt;s:TextInput x="77" y="13" includeIn="loggedOut" id="username"/&gt;</code></p>
<p><code> </code></p>
<p>Change To:</p>
<p><code> </code></p>
<p><code>&lt;s:TextInput x="110" y="10" id="username" change="loggedOut_changeHandler(event)" includeIn="loggedOut"/&gt;</code></p>
<p><code> </code></p>
<p>Change From:</p>
<p><code> </code></p>
<p><code>&lt;s:TextInput x="77" y="43" displayAsPassword="true" includeIn="loggedOut" displayAsPassword="true" id="password"/&gt;</code></p>
<p><code> </code></p>
<p>Change To:</p>
<p><code> </code></p>
<p><code>&lt;s:TextInput x="110" y="40" id="password" change="loggedOut_changeHandler(event)" displayAsPassword="true" includeIn="loggedOut"/&gt;</code></p>
<p><code> </code></p>
<p>Change From:</p>
<p><code> </code></p>
<p><code>&lt;s:Button x="8" y="72" label="Login" click="login_user.send();" includeIn="loggedOut"/&gt;</code></p>
<p><code> </code></p>
<p>Change To:</p>
<p><code> </code></p>
<p><code>&lt;s:Button x="10" y="72" id="loginBtn" label="Login" click="login_user.send();" enabled="false" includeIn="loggedOut"/&gt;</code></p>
<p><code> </code></p>
<p>Note: In the above code we have chosen to call <code>loggedOut_changeHandler</code> using the <code>change</code> event for the TextInput field. There are other events we could have chosen such as <code>focusOut</code>. The reason we are using the change event however, is so that as soon as the field has met the validation, the &#8220;Login&#8221; button will become enabled rather than waiting for the user to leave the TextInput field. It could be argued that this takes more system resources because it is checking validation on every text change, but the difference is really negligible. Nevertheless, use the method you feel most comfortable with.</p>
<p>Step 2. Validation Function</p>
<p>The function <code>loggedOut_changeHandler</code> could have been split up into two separate functions and would normally be written that way if we were not basing the login button enabled property on the validation of multiple TextInput fields.</p>
<pre>protected function loggedOut_changeHandler(event:TextOperationEvent):void
  {
  if (username.text)
  {
  var valUsername:ValidationResultEvent;
  usernameVal.source = username;
  usernameVal.property = "text";
  usernameVal.minLength=6;
  }
  if (password.text)
  {
  var valPassword:ValidationResultEvent;
  passwordVal.source = password;
  passwordVal.property = "text";
  passwordVal.minLength=6;
  }
  valUsername = usernameVal.validate();
  valPassword = passwordVal.validate();
  if(valUsername.type == "valid" &amp;&amp; valPassword.type == "valid")
  loginBtn.enabled = true;
  else
  loginBtn.enabled = false;
  }</pre>
<p>Step 3. Changes to <code>getCookie_resultHandler</code></p>
<p>Because you have the username and password TextInput boxes set to validate on the change event, when a cookie is set, the &#8220;Login&#8221; button is disabled and the only way to enable it is to make a change in one of the text boxes. To avoid this little problem, we have set <code>loginBtn.enable = true;</code>. We can do this because now that we are validating, we know that any cookie set will have already undergone validation. The <code>getCookie_resultHandler</code> should now look like:</p>
<pre>protected function getCookie_resultHandler(event:ResultEvent):void
  {
  if(event.result.storedCookie == true)
  {
  cookieAction = true;
  username.text = event.result.creds.username;
  password.text = event.result.creds.password;
  loginBtn.enabled = true;
  }
  else
  {
  cookieAction == false;
  }
  }</pre>
<p>Step 4. Run and Test the application. Check to make sure that it is working both with and without the cookie set.</p>
<p><a href="http://blog.anaara.com/wp-content/uploads/2011/02/CLB5-1.gif"><img class="alignleft size-medium wp-image-408" src="http://blog.anaara.com/wp-content/uploads/2011/02/CLB5-1-300x121.gif" alt="Flex 4 - textInput Validation" width="300" height="121" /></a></p>
<p><strong>&#8220;forgotPW&#8221; State Validation</strong></p>
<p>In this section we will check for validation on the email address of the forgotPW state. Here we are only checking to make sure that the email address is formatted correctly, not wether it is a working email address or not.</p>
<p>Tip: For more information on the validation criteria, you can view EmailValidator.as by holding Command and clicking &#8220;EmailValidator&#8221; in the import statement.</p>
<p>Step 1. Changes to State Components</p>
<p>Change From:</p>
<p><code> </code></p>
<p><code>&lt;s:TextInput x="110" y="39" id="email_to" includeIn="forgotPW"/&gt;</code></p>
<p><code> </code></p>
<p>Change To:</p>
<p><code> </code></p>
<p><code>&lt;s:TextInput x="110" y="39" id="email_to" change="email_to_changeHandler(event)" includeIn="forgotPW"/&gt;</code></p>
<p><code> </code></p>
<p>Change From:</p>
<p><code> </code></p>
<p><code>&lt;s:Button x="8" y="72" label="Get Login Info" click="get_password.send();" includeIn="forgotPW"/&gt;</code></p>
<p><code> </code></p>
<p>Change To:</p>
<p><code> </code></p>
<p><code>&lt;s:Button x="8" y="72" id="emailBtn" label="Get Login Info" click="get_password.send();" enabled="false" includeIn="forgotPW"/&gt;</code></p>
<p><code> </code></p>
<p>Step 2. Validation Function</p>
<pre>protected function email_to_changeHandler(event:TextOperationEvent):void
  {
  if (email_to.text)
  {
  var valEmail:ValidationResultEvent;
  emailVal.source = email_to;
  emailVal.property = "text";
  }

 valEmail = emailVal.validate();
  if(valEmail.type == "valid")
  emailBtn.enabled = true;
  else
  emailBtn.enabled = false;
  }</pre>
<p><a href="http://blog.anaara.com/wp-content/uploads/2011/02/CLB5-2.gif"><img class="alignleft size-medium wp-image-407" src="http://blog.anaara.com/wp-content/uploads/2011/02/CLB5-2-300x121.gif" alt="Flex 4 - Email Validation" width="300" height="121" /></a></p>
<p><strong>&#8220;register&#8221; State Validation</strong></p>
<p>The register state is a combination of the above since we have the same textInput fields as we had in the first two section, just all in one state now.</p>
<p>Step 1. Changes to State Components</p>
<p>Change From:</p>
<p><code> </code></p>
<p><code>&lt;s:TextInput x="110" y="24" id="usernameTextInput2" text="{users.username}" includeIn="register"/&gt;</code></p>
<p><code> </code></p>
<p>Change To:</p>
<p><code> </code></p>
<p><code>&lt;s:TextInput x="110" y="24" id="usernameTextInput2" text="{users.username}" change="registerVal_changeHandler(event)" includeIn="register"/&gt;</code></p>
<p><code> </code></p>
<p>Change From:</p>
<p><code> </code></p>
<p><code>&lt;s:TextInput x="110" y="54" id="emailTextInput2" text="{users.email}" includeIn="register"/&gt;</code></p>
<p><code>Change To:</code></p>
<p><code> </code><br />
<code> </code></p>
<p><code>&lt;s:TextInput x="110" y="54" id="emailTextInput2" text="{users.email}" change="registerVal_changeHandler(event)" includeIn="register"/&gt;</code></p>
<p><code> </code></p>
<p>Change From:</p>
<p><code> </code></p>
<p><code>&lt;s:TextInput x="110" y="84" id="passwordTextInput2" text="{users.password}" displayAsPassword="true" includeIn="register"/&gt;</code></p>
<p><code>Change To:</code></p>
<p><code> </code></p>
<p><code>&lt;s:TextInput x="110" y="84" id="passwordTextInput2" text="{users.password}" change="registerVal_changeHandler(event)" displayAsPassword="true" includeIn="register"/&gt;</code></p>
<p><code> </code></p>
<p>Change From:</p>
<p><code> </code></p>
<p><code>&lt;s:Button x="10" y="118" label="Save" id="saveBtn" click="saveBtn_clickHandler(event)" includeIn="register"/&gt;</code></p>
<p><code> </code></p>
<p>Change To:</p>
<p><code> </code></p>
<p><code>&lt;s:Button x="10" y="118" label="Save" id="saveBtn" click="saveBtn_clickHandler(event)" enabled="false" includeIn="register"/&gt;</code></p>
<p><code> </code></p>
<p>Step 2. Validation Function</p>
<pre>protected function registerVal_changeHandler(event:TextOperationEvent):void
  {

  if (usernameTextInput2.text)
  {
  var valUsername2:ValidationResultEvent;
  usernameVal2.source = usernameTextInput2;
  usernameVal2.property = "text";
  usernameVal2.minLength=6;
  }

 if (emailTextInput2.text)
  {
  var valEmail2:ValidationResultEvent;
  emailVal2.source = emailTextInput2;
  emailVal2.property = "text";
  }

 if (passwordTextInput2.text)
  {
  var valPassword2:ValidationResultEvent;
  passwordVal2.source = passwordTextInput2;
  passwordVal2.property = "text";
  passwordVal2.minLength=6;
  }

 valUsername2 = usernameVal2.validate();
  valEmail2 = emailVal2.validate();
  valPassword2 = passwordVal2.validate();
  if(valUsername2.type == "valid" &amp;&amp; valPassword2.type == "valid" &amp;&amp; valEmail2.type == "valid")
  saveBtn.enabled = true;
  else
  saveBtn.enabled = false;
  }</pre>
<p><a href="http://blog.anaara.com/wp-content/uploads/2011/02/CLB5-3.gif"><img class="alignleft size-medium wp-image-406" src="http://blog.anaara.com/wp-content/uploads/2011/02/CLB5-3-300x121.gif" alt="Flex 4 - textInput and Email Validation" width="300" height="121" /></a></p>
<p>That&#8217;s it! Go ahead and save and run your application and check your validation in all three states. Make sure everything is working correctly. Your new application should look like:</p>
<pre>&lt;?xml version="1.0" encoding="utf-8"?&gt;
  &lt;s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"
  xmlns:s="library://ns.adobe.com/flex/spark"
  xmlns:mx="library://ns.adobe.com/flex/mx"
  applicationComplete="init()"
  minWidth="955" minHeight="600" xmlns:valueObjects="valueObjects.*"
  xmlns:usersservice="services.usersservice.*"&gt;
  &lt;fx:Script&gt;
  &lt;![CDATA[
  import mx.controls.Alert;
  import mx.events.ValidationResultEvent;
  import mx.rpc.events.ResultEvent;
  import mx.validators.EmailValidator;
  import mx.validators.StringValidator;

  import spark.events.TextOperationEvent;

  private var userid:int;
  private var usertype:String;

  private var usernameVal:StringValidator = new StringValidator();
  private var passwordVal:StringValidator = new StringValidator();

  private var emailVal:EmailValidator = new EmailValidator();

  private var usernameVal2:StringValidator = new StringValidator();
  private var emailVal2:EmailValidator = new EmailValidator();
  private var passwordVal2:StringValidator = new StringValidator();

  [Bindable]
  private var cookieAction:Boolean;

  protected function saveBtn_clickHandler(event:MouseEvent):void
  {
  var users2:Users = new Users();
  users2.username = usernameTextInput2.text;
  users2.email = emailTextInput2.text;
  users2.password = passwordTextInput2.text;
  users2.user_type = "user";

  createUsersResult.token = usersService.createUsers(users2);
  createUsersResult.token = usersService.commit();
  currentState = 'loggedOut';
  }

  private function checkLogin(event:ResultEvent):void
  {
  userid = event.result.loginsuccess;
  trace (userid);
  usertype = event.result.usertype;
  trace (usertype);
  cookieAction = event.result.usertype;
  trace (cookieAction);
  if (userid != 0)
  {
  currentState = usertype;
  }
  else
  {
  mx.controls.Alert.show('Invalid username/password');
  }
  }

  protected function createUsersResult_resultHandler(event:ResultEvent):void
  {
  mx.controls.Alert.show('Thank you for registering. You may login now!');
  currentState = "loggedOut";
  }

  private function init():void
  {
  getCookie.send();
  }

 protected function getCookie_resultHandler(event:ResultEvent):void
  {
  if(event.result.storedCookie == true)
  {
  cookieAction = true;
  username.text = event.result.creds.username;
  password.text = event.result.creds.password;
  loginBtn.enabled = true;
  }
  else
  {
  cookieAction == false;
  }
  }

  private function getPassword(event:ResultEvent):void
  {

  if(event.result.getPassword == "yes")
  {
  mx.controls.Alert.show('Your password has been emailed to you.');
  currentState = "loggedOut";
  }
  else
  {
  mx.controls.Alert.show('Invalid email, please try again.');
  }
  }

 protected function loggedOutVal_changeHandler(event:TextOperationEvent):void
  {

  if (username.text)
  {
  var valUsername:ValidationResultEvent;
  usernameVal.source = username;
  usernameVal.property = "text";
  usernameVal.minLength=6;
  }

  if (password.text)
  {
  var valPassword:ValidationResultEvent;
  passwordVal.source = password;
  passwordVal.property = "text";
  passwordVal.minLength=6;
  }

  valUsername = usernameVal.validate();
  valPassword = passwordVal.validate();
  if(valUsername.type == "valid" &amp;&amp; valPassword.type == "valid")
  loginBtn.enabled = true;
  else
  loginBtn.enabled = false;
  }

 protected function email_toVal_changeHandler(event:TextOperationEvent):void
  {
  if (email_to.text)
  {
  var valEmail:ValidationResultEvent;
  emailVal.source = email_to;
  emailVal.property = "text";
  }

  valEmail = emailVal.validate();
  if(valEmail.type == "valid")
  emailBtn.enabled = true;
  else
  emailBtn.enabled = false;
  }

 protected function registerVal_changeHandler(event:TextOperationEvent):void
  {

  if (usernameTextInput2.text)
  {
  var valUsername2:ValidationResultEvent;
  usernameVal2.source = usernameTextInput2;
  usernameVal2.property = "text";
  usernameVal2.minLength=6;
  }

  if (emailTextInput2.text)
  {
  var valEmail2:ValidationResultEvent;
  emailVal2.source = emailTextInput2;
  emailVal2.property = "text";
  }

  if (passwordTextInput2.text)
  {
  var valPassword2:ValidationResultEvent;
  passwordVal2.source = passwordTextInput2;
  passwordVal2.property = "text";
  passwordVal2.minLength=6;
  }

  valUsername2 = usernameVal2.validate();
  valEmail2 = emailVal2.validate();
  valPassword2 = passwordVal2.validate();
  if(valUsername2.type == "valid" &amp;&amp; valPassword2.type == "valid" &amp;&amp; valEmail2.type == "valid")
  saveBtn.enabled = true;
  else
  saveBtn.enabled = false;
  }

 ]]&gt;
  &lt;/fx:Script&gt;
  &lt;s:states&gt;
  &lt;s:State name="loggedOut"/&gt;
  &lt;s:State name="forgotPW"/&gt;
  &lt;s:State name="register"/&gt;
  &lt;s:State name="user"/&gt;
  &lt;s:State name="admin"/&gt;
  &lt;/s:states&gt;
  &lt;fx:Declarations&gt;
  &lt;s:HTTPService id="login_user" result="checkLogin(event)" showBusyCursor="true" method="POST"
  url="login.php" useProxy="false"&gt;
  &lt;s:request xmlns=""&gt;
  &lt;username&gt;
  {username.text}
  &lt;/username&gt;
  &lt;password&gt;
  {password.text}
  &lt;/password&gt;
  &lt;logincookie&gt;
  {setCookie.selected}
  &lt;/logincookie&gt;
  &lt;/s:request&gt;
  &lt;/s:HTTPService&gt;

  &lt;s:HTTPService id="getCookie" result="getCookie_resultHandler(event)" method="POST" url="getCookie.php"/&gt;

  &lt;mx:HTTPService id="get_password" result="getPassword(event)" showBusyCursor="true" method="POST"
  url="forgotPW.php" useProxy="false"&gt;
  &lt;mx:request xmlns=""&gt;
  &lt;email_to&gt;
  {email_to.text}
  &lt;/email_to&gt;
  &lt;/mx:request&gt;
  &lt;/mx:HTTPService&gt;

  &lt;valueObjects:Users id="users"/&gt;
  &lt;usersservice:UsersService id="usersService" fault="Alert.show(event.fault.faultString + '\n' + event.fault.faultDetail)" showBusyCursor="true"/&gt;
  &lt;s:CallResponder id="createUsersResult" result="createUsersResult_resultHandler(event)"/&gt;
  &lt;!-- Place non-visual elements (e.g., services, value objects) here --&gt;
  &lt;/fx:Declarations&gt;
  &lt;s:Panel width="250" height="200" title="Flex 4 Login Box" horizontalCenter="0" verticalCenter="0"&gt;
  &lt;s:Label x="10" y="18" text="Username" includeIn="loggedOut"/&gt;
  &lt;s:TextInput x="110" y="10" id="username" change="loggedOutVal_changeHandler(event)" includeIn="loggedOut"/&gt;
  &lt;s:Label x="12" y="47" text="Password" includeIn="loggedOut"/&gt;
  &lt;s:TextInput x="110" y="40" id="password" change="loggedOutVal_changeHandler(event)" displayAsPassword="true" includeIn="loggedOut"/&gt;
  &lt;s:Button x="10" y="72" id="loginBtn" label="Login" click="login_user.send();" enabled="false" includeIn="loggedOut"/&gt;
  &lt;s:Button x="120" y="72" label="Forgot Login Info?" click="currentState='forgotPW'" includeIn="loggedOut"/&gt;
  &lt;s:CheckBox x="10" y="101" label="Remember Me" id="setCookie" selected="{cookieAction}" includeIn="loggedOut"/&gt;
  &lt;s:Label x="195" y="103" text="Sign Up" click="currentState='register'" includeIn="loggedOut"/&gt;

  &lt;s:Label x="10" y="46" text="Email:" includeIn="forgotPW"/&gt;
  &lt;s:TextInput x="110" y="39" id="email_to" change="email_toVal_changeHandler(event)" includeIn="forgotPW"/&gt;
  &lt;s:Button x="8" y="72" id="emailBtn" label="Get Login Info" click="get_password.send();" enabled="false" includeIn="forgotPW"/&gt;
  &lt;s:Button x="168" y="72" label="&amp;lt;&amp;lt; Login" click="currentState='loggedOut'" includeIn="forgotPW"/&gt;

  &lt;s:Label x="10" y="31" text="Username:" includeIn="register"/&gt;
  &lt;s:TextInput x="110" y="24" id="usernameTextInput2" text="{users.username}" change="registerVal_changeHandler(event)" includeIn="register"/&gt;
  &lt;s:Label x="10" y="61" text="Email:" includeIn="register"/&gt;
  &lt;s:TextInput x="110" y="54" id="emailTextInput2" text="{users.email}" change="registerVal_changeHandler(event)" includeIn="register"/&gt;
  &lt;s:Label x="10" y="91" text="Password:" includeIn="register"/&gt;
  &lt;s:TextInput x="110" y="84" id="passwordTextInput2" text="{users.password}" change="registerVal_changeHandler(event)" displayAsPassword="true" includeIn="register"/&gt;
  &lt;s:Button x="10" y="118" label="Save" id="saveBtn" click="saveBtn_clickHandler(event)" enabled="false" includeIn="register"/&gt;
  &lt;s:Button x="168" y="118" label="&amp;lt;&amp;lt; Login" click="currentState='loggedOut'" includeIn="register"/&gt;

  &lt;s:Label x="10" y="10" text="Welcome User" includeIn="user"/&gt;
  &lt;s:Button x="10" y="30" label="Log Out" click="currentState='loggedOut'" includeIn="user"/&gt;

  &lt;s:Label x="10" y="10" text="Welcome Admin" includeIn="admin"/&gt;
  &lt;s:Button x="10" y="30" label="Admin Log Out" click="currentState='loggedOut'" includeIn="admin"/&gt;
  &lt;/s:Panel&gt;
  &lt;/s:Application&gt;</pre>
]]></content:encoded>
			<wfw:commentRss>http://blog.anaara.com/archives/399/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Customizing the Login Box – Part 2 – Implementing &#8220;Forgot Password&#8221; with Flash Builder, PHP and MySql</title>
		<link>http://blog.anaara.com/archives/395</link>
		<comments>http://blog.anaara.com/archives/395#comments</comments>
		<pubDate>Thu, 03 Mar 2011 19:59:48 +0000</pubDate>
		<dc:creator>Dan Orlando</dc:creator>
				<category><![CDATA[ActionScript]]></category>
		<category><![CDATA[Adobe]]></category>
		<category><![CDATA[Flash]]></category>
		<category><![CDATA[Flex]]></category>
		<category><![CDATA[Flex 4]]></category>
		<category><![CDATA[php]]></category>
		<category><![CDATA[RIA]]></category>

		<guid isPermaLink="false">http://blog.anaara.com/?p=395</guid>
		<description><![CDATA[In this tutorial, you will implement forgotten password functionality to a login box. The overall goal here is for the user to enter there email address into a TextInput field and have a PHP service check the database for a &#8230; <a href="http://blog.anaara.com/archives/395">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>In this tutorial, you will implement forgotten password functionality to a login box.  The overall goal here is for the user to enter there email address into a TextInput field and have a PHP service check the database for a match, then send the username and password for that user to the email address provided if it exists in the db. If no match is found, it will alert the user that there was no match found.</p>
<p>The first thing we are going to need is the PHP service that will handle the request from the client side.</p>
<p>NOTE: If you are using MAMP and not MAMP Pro, you will not be able to send emails. So to check this functionality, either test on another server or upgrade and configure your application for MAMP Pro.</p>
<pre>&lt;?

$host="localhost"; // Host name

  $username="root"; // Mysql username

  $password="root"; // Mysql password

$db_name="example12"; // Database name

//Connect to server and select databse.

  mysql_connect("$host", "$username", "$password")or die("cannot connect to server");

  mysql_select_db("$db_name")or die("cannot select DB");

// value sent from form

  $email_to = mysql_real_escape_string($_POST["email_to"]);

// table name

  $tbl_name=users;

// retrieve password from table where e-mail = $email_to(mark@phpeasystep.com)

  $sql="SELECT password FROM $tbl_name WHERE email='$email_to'";

  $result=mysql_query($sql);

// If there is an email match, it must be in one single row, then keep the value in the variable "$count"

  $count=mysql_num_rows($result);

// compare if $count =1 row

  if($count==1){

  $rows=mysql_fetch_array($result);

// keep password in $your_password

  $your_password=$rows['password'];

// ---------------- SEND MAIL FORM ----------------

  $to=$email_to; // Who the email will be sent to

  $subject="Your Password"; // Email subject

  $header="from: CreativeRIA &lt;jeff@creativeria.com&gt;"; // From is the email being sent from

  $messages.="Your password is $your_password \r\n"; // What is body of the message?

  $sentmail = mail($to,$subject,$messages,$header); // Send email

  }

//start outputting the XML

  $output = "&lt;getPassword&gt;";

//If an email was sent then output yes else output no

  if($sentmail)

  $output .= "yes"; 

  else

  $output .= "no"; 

  $output .= "&lt;/getPassword&gt;";

//output all the XML

  print ($output);

?&gt;</pre>
<p>In English, this PHP code says: Take the &#8220;email_to&#8221; variable being passed by Flex and check the &#8220;users&#8221; table of the database and see if there is a match. If there is, then send an email to the user with their password and send a response of &#8220;yes&#8221; back to the client. If there is no match found, then send a &#8220;no&#8221; response to the client. The client side is then responsible for deciding what to do with the response.</p>
<p>Changes in FB4</p>
<p>Step 1. We need to write the function that will handle the &#8220;yes&#8221; or &#8220;no&#8221; from PHP &#8211; <code>print ($output);</code></p>
<pre>private function getPassword(event:ResultEvent):void

  {

  if(event.result.getPassword == "yes")

  {

  mx.controls.Alert.show('Your password has been emailed to you.');

  currentState = "loggedOut";

  }

  else

  {

  mx.controls.Alert.show('Invalid email, please try again.');

  } 

  }</pre>
<p>In English, the code says says: if <code>event.result.getPassword</code> (what is being sent back from the server) is &#8220;yes&#8221;, then show the message in an Alert box and take the user to the &#8220;loggedOut&#8221; state. Otherwise, show the invalid message in an Alert box.</p>
<p>Step 2. Write the HTTPService that will be initiated by the button click from the &#8220;Get Info&#8221; button on the &#8220;Get Login Info&#8221; state. This service will call the &#8220;getPassword&#8221; function written in Step 1, know the location of forgotPW.php, the method of communication, and what the name of the variable we are sending to PHP.</p>
<pre>&lt;mx:HTTPService id="get_password" result="getPassword(event)" showBusyCursor="true" method="POST" url="forgotPW.php" useProxy="false"&gt;

  &lt;mx:request xmlns=""&gt;

  &lt;email_to&gt;

  {email_to.text}

  &lt;/email_to&gt;

  &lt;/mx:request&gt;

  &lt;/mx:HTTPService&gt;</pre>
<p>Step 4. Make the &#8220;Get Login Info&#8221; button call the HTTPService rather than just taking the user to the &#8220;loggedOut&#8221; state as it is now.</p>
<p>Change From:</p>
<pre>&lt;s:Button x="10" y="72" label="Get Login Info" includeIn="forgotPW"/&gt;</pre>
<p>Change To:</p>
<pre>&lt;s:Button x="8" y="72" label="Get Login Info" click="get_password.send();" includeIn="forgotPW"/&gt;</pre>
<p>If you have been following along with these tutorials, your application should look similar to:</p>
<pre>&lt;?xml version="1.0" encoding="utf-8"?&gt;

  &lt;s:Application xmlns:fx="http://ns.adobe.com/mxml/2009" 

  xmlns:s="library://ns.adobe.com/flex/spark" 

  xmlns:mx="library://ns.adobe.com/flex/mx"

  applicationComplete="init()"

  minWidth="955" minHeight="600" xmlns:valueObjects="valueObjects.*"

  xmlns:usersservice="services.usersservice.*"&gt;

  &lt;fx:Script&gt;

  &lt;![CDATA[

  import mx.controls.Alert;

  import mx.rpc.events.ResultEvent;

  private var userid:int;

  private var usertype:String;

  [Bindable]

  private var cookieAction:Boolean;

  protected function saveBtn_clickHandler(event:MouseEvent):void

  {

  var users2:Users = new Users();

  users2.username = usernameTextInput2.text;

  users2.email = emailTextInput2.text;

  users2.password = passwordTextInput2.text;

  users2.user_type = "user";

  createUsersResult.token = usersService.createUsers(users2);

  createUsersResult.token = usersService.commit();

  currentState = 'loggedOut'; 

  }

  private function checkLogin(event:ResultEvent):void

  {

  userid = event.result.loginsuccess;

  trace (userid);

  usertype = event.result.usertype;

  trace (usertype);

  cookieAction = event.result.usertype;

  trace (cookieAction);

  if (userid != 0)

  {

  currentState = usertype;

  }

  else

  {

  mx.controls.Alert.show('Invalid username/password');

  }

  }

  protected function createUsersResult_resultHandler(event:ResultEvent):void

  {

  mx.controls.Alert.show('Thank you for registering. You may login now!');

  currentState = "loggedOut";

  }

  private function init():void

  {

  getCookie.send();

  }

 protected function getCookie_resultHandler(event:ResultEvent):void

  {

  if(event.result.storedCookie == true)

  {

  cookieAction = true;

  username.text = event.result.creds.username;

  password.text = event.result.creds.password;

  }

  else

  {

  cookieAction == false;

  }

  }

  private function getPassword(event:ResultEvent):void

  {

  if(event.result.getPassword == "yes")

  {

  mx.controls.Alert.show('Your password has been emailed to you.');

  currentState = "loggedOut";

  }

  else

  {

  mx.controls.Alert.show('Invalid email, please try again.');

  } 

  }

  ]]&gt;

  &lt;/fx:Script&gt;

  &lt;s:states&gt;

  &lt;s:State name="loggedOut"/&gt;

  &lt;s:State name="forgotPW"/&gt;

  &lt;s:State name="register"/&gt;

  &lt;s:State name="user"/&gt;

  &lt;s:State name="admin"/&gt;

  &lt;/s:states&gt;

  &lt;fx:Declarations&gt;

  &lt;s:HTTPService id="login_user" result="checkLogin(event)" showBusyCursor="true" method="POST"

  url="login.php" useProxy="false"&gt;

  &lt;s:request xmlns=""&gt;

  &lt;username&gt;

  {username.text}

  &lt;/username&gt;

  &lt;password&gt;

  {password.text}

  &lt;/password&gt;

  &lt;logincookie&gt;

  {setCookie.selected}

  &lt;/logincookie&gt;

  &lt;/s:request&gt;

  &lt;/s:HTTPService&gt;

  &lt;s:HTTPService id="getCookie" result="getCookie_resultHandler(event)" method="POST" url="getCookie.php"/&gt;

  &lt;mx:HTTPService id="get_password" result="getPassword(event)" showBusyCursor="true" method="POST"

  url="forgotPW.php" useProxy="false"&gt;

  &lt;mx:request xmlns=""&gt;

  &lt;email_to&gt;

  {email_to.text}

  &lt;/email_to&gt;

  &lt;/mx:request&gt;

  &lt;/mx:HTTPService&gt;

  &lt;valueObjects:Users id="users"/&gt;

  &lt;usersservice:UsersService id="usersService" fault="Alert.show(event.fault.faultString + '\n' + event.fault.faultDetail)" showBusyCursor="true"/&gt;

  &lt;s:CallResponder id="createUsersResult" result="createUsersResult_resultHandler(event)"/&gt;

  &lt;!-- Place non-visual elements (e.g., services, value objects) here --&gt;

  &lt;/fx:Declarations&gt;

  &lt;s:Panel width="250" height="200" title="Flex 4 Login Box" horizontalCenter="0" verticalCenter="0"&gt;

  &lt;s:Label x="10" y="18" text="Username" includeIn="loggedOut"/&gt;

  &lt;s:TextInput x="110" y="10" id="username" includeIn="loggedOut"/&gt;

  &lt;s:Label x="12" y="47" text="Password" includeIn="loggedOut"/&gt;

  &lt;s:TextInput x="110" y="40" id="password" displayAsPassword="true" includeIn="loggedOut"/&gt;

  &lt;s:Button x="10" y="72" label="Login" click="login_user.send();" includeIn="loggedOut"/&gt;

  &lt;s:Button x="120" y="72" label="Forgot Login Info?" click="currentState='forgotPW'" includeIn="loggedOut"/&gt;

  &lt;s:CheckBox x="10" y="101" label="Remember Me" id="setCookie" selected="{cookieAction}" includeIn="loggedOut"/&gt;

  &lt;s:Label x="195" y="103" text="Sign Up" click="currentState='register'" includeIn="loggedOut"/&gt;

  &lt;s:Label x="10" y="46" text="Email:" includeIn="forgotPW"/&gt;

  &lt;s:TextInput x="110" y="39" id="email_to" includeIn="forgotPW"/&gt;

  &lt;s:Button x="8" y="72" label="Get Login Info" click="get_password.send();" includeIn="forgotPW"/&gt;

  &lt;s:Button x="168" y="72" label="&amp;lt;&amp;lt; Login" click="currentState='loggedOut'" includeIn="forgotPW"/&gt;

  &lt;s:Label x="10" y="31" text="Username:" includeIn="register"/&gt;

  &lt;s:TextInput x="110" y="24" id="usernameTextInput2" text="{users.username}" includeIn="register"/&gt;

  &lt;s:Label x="10" y="61" text="Email:" includeIn="register"/&gt;

  &lt;s:TextInput x="110" y="54" id="emailTextInput2" text="{users.email}" includeIn="register"/&gt;

  &lt;s:Label x="10" y="91" text="Password:" includeIn="register"/&gt;

  &lt;s:TextInput x="110" y="84" id="passwordTextInput2" text="{users.password}" displayAsPassword="true" includeIn="register"/&gt;

  &lt;s:Button x="10" y="118" label="Save" id="saveBtn" click="saveBtn_clickHandler(event)" includeIn="register"/&gt;

  &lt;s:Button x="168" y="118" label="&amp;lt;&amp;lt; Login" click="currentState='loggedOut'" includeIn="register"/&gt;

  &lt;s:Label x="10" y="10" text="Welcome User" includeIn="user"/&gt;

  &lt;s:Button x="10" y="30" label="Log Out" click="currentState='loggedOut'" includeIn="user"/&gt;

  &lt;s:Label x="10" y="10" text="Welcome Admin" includeIn="admin"/&gt;

  &lt;s:Button x="10" y="30" label="Admin Log Out" click="currentState='loggedOut'" includeIn="admin"/&gt;

  &lt;/s:Panel&gt;

  &lt;/s:Application&gt;</pre>
]]></content:encoded>
			<wfw:commentRss>http://blog.anaara.com/archives/395/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Customizing the Login Box &#8211; Part 1 &#8211; Setting a &#8220;Remember Me&#8221; Cookie &#8211; FB4, PHP and MySql</title>
		<link>http://blog.anaara.com/archives/366</link>
		<comments>http://blog.anaara.com/archives/366#comments</comments>
		<pubDate>Wed, 23 Feb 2011 15:15:37 +0000</pubDate>
		<dc:creator>Dan Orlando</dc:creator>
				<category><![CDATA[ActionScript]]></category>
		<category><![CDATA[Adobe]]></category>
		<category><![CDATA[Flash]]></category>
		<category><![CDATA[Flex]]></category>
		<category><![CDATA[Flex 4]]></category>
		<category><![CDATA[mySQL]]></category>
		<category><![CDATA[php]]></category>
		<category><![CDATA[RIA]]></category>

		<guid isPermaLink="false">http://blog.anaara.com/?p=366</guid>
		<description><![CDATA[In this tutorial you will learn how to add a &#8220;Remember Me&#8221; check box to your current login component, or into the login app that we built in the two-part tutorial, &#8220;Creating a Login Box&#8221;. Either way, by the end &#8230; <a href="http://blog.anaara.com/archives/366">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>In this tutorial you will learn how to add a &#8220;Remember Me&#8221; check box to your current login component, or into the login app that we built in the two-part tutorial, &#8220;Creating a Login Box&#8221;. Either way, by the end of this tutorial you will have what you need to successfully integrate this functionality. It is worth noting that while this can also be done using shared objects, we will build this feature into the login component by using PHP to set a cookie on the local machine instead.</p>
<p>You will begin by adding a &#8220;Remember Me&#8221; check box onto the login state of the component. For our login box, this is the &#8220;loggedOut&#8221; state. You are going to use PHP to set the cookie on the local machine. There are going to be three variables that you&#8217;ll need to make this happen.</p>
<p>1. Username (Get)</p>
<p>2. Password (Get)</p>
<p>3. Cookie &#8211; True/False (Set)</p>
<p><strong>Setting the Cookie</strong></p>
<p>There are a couple of things that will need to happen here. First, you will have to create a new variable to pass to the server to let it know if the checkbox is checked or not, and then tell PHP what to do about it. Start by adding the code below to your login.php file you created in the last tutorial, which will set the cookie.</p>
<pre>  &lt;?php

define( "DATABASE_SERVER", "localhost" );
  define( "DATABASE_USERNAME", "root" );
  define( "DATABASE_PASSWORD", "root" );
  define( "DATABASE_NAME", "example12" );

//connect to the database
  $mysql = mysql_connect(DATABASE_SERVER, DATABASE_USERNAME, DATABASE_PASSWORD) or die(mysql_error());

//select the database
  mysql_select_db( DATABASE_NAME );

//These are the variables that Flex is passing to PHP
  $username = mysql_real_escape_string($_POST["username"]);
  $password = mysql_real_escape_string($_POST["password"]);
  $logincookie = mysql_real_escape_string($_POST["logincookie"]); //New

//Check the credentials
  $query = "SELECT * FROM users WHERE username = '$username' AND password = '$password'";
  $result = mysql_fetch_array(mysql_query($query));

//Output the returned query in XML: If returned false output 0 else output the users id
  $output = "&lt;loginsuccess&gt;";
  if(!$result)
  {
  $output .= "0";
  }else{
  $output .= $result['id'];
  }
  $output .= "&lt;/loginsuccess&gt;";

//Output the User Type
  $usrtyp .= "&lt;usertype&gt;";
  $usrtyp .= $result['user_type'];
  $usrtyp .= "&lt;/usertype&gt;";

//This Section is New (start)
  //If the checkbox is checked (true) set cookie, else (false) delete cookie
  if($logincookie == "true")
  {
  setcookie("username", $username, time()+3600);
  setcookie("password", $password, time()+3600);
  }else{
  setcookie("username", "", time()-1);
  setcookie("password", "", time()-1);
  }
  //This Section is New (end)

//output all the XML

print ($output);
  print ($usrtyp);
  print ($lcook); //New

?&gt;</pre>
<p>If you compare this login.php file to the previous one, you will see that we have added $logincookie, written the query, an if/else statement with instructions on what to do with it, and passed the information back to Flex by printing $lcook.</p>
<p>Note: you are passing back $lcook as an easy self-check so that we can see it in the FB4 console when running the application in debug mode, but this isn&#8217;t critical in order for the functionality to work.</p>
<p>Now with the login.php file saved, switch back to FB4 to make a few necessary changes which will assist in setting the cookie.</p>
<p>1. Create a variable so that you can trace the response from the server when setting the cookie.</p>
<p><code>[Bindable]<br />
private var cookieAction:Boolean;</code></p>
<p>2. Add an id to the CheckBox of setcookie. <code>&lt;s:CheckBox x="10" y="101" label="Remember Me" id="setCookie" includeIn="loggedOut"/&gt;</code></p>
<p>3. Add a new variable in the login_user HTTPService that will tell PHP if the box is checked or not. By default a CheckBox value is true/false.</p>
<pre>  &lt;logincookie&gt;
  {setCookie.selected}
  &lt;/logincookie&gt;</pre>
<p>4. (Optional) lets go ahead and place a trace on the variable cookieAction so that we can make sure everything is being sent back correctly. In the checkLogin function add the following lines:</p>
<pre>  cookieAction = event.result.usertype;
  trace (cookieAction);</pre>
<p>It should now look like this&#8230;</p>
<pre>  private function checkLogin(event:ResultEvent):void
  {
  userid = event.result.loginsuccess;
  trace (userid);
  usertype = event.result.usertype;
  trace (usertype);
  cookieAction = event.result.usertype;
  trace (cookieAction);
  if (userid != 0)
  {
  currentState = usertype;
  }
  else
  {
  mx.controls.Alert.show('Invalid username/password');
  }
  }</pre>
<p>Ok go ahead and run the application in debug mode. Then login using either admin or user credentials. Once you are logged in, close the browser and while looking in the console you should see three variables passed back from PHP. It is these variables that our application will use to determine the response.</p>
<p>1. number &#8211; as long as this id is not 0, you will be allowed to login</p>
<p>2. user or admin &#8211; this is telling the application which state to send you to</p>
<p>3. true/false &#8211; This is a check telling us weather or not the cookie variable was passed successfully.</p>
<p><a href="http://blog.anaara.com/wp-content/uploads/2011/02/CLB3-2.gif"></a><a href="http://blog.anaara.com/wp-content/uploads/2011/02/CLB3-1.gif"><img class="alignleft size-medium wp-image-391" src="http://blog.anaara.com/wp-content/uploads/2011/02/CLB3-1-300x82.gif" alt="Flex 4 - Customizing a Login Box using FB4, PHP, and mySQL - Console Tab" width="300" height="82" /></a></p>
<p>Tip: If you would like to be able to see the cookie you can use the &#8220;Web Developer&#8221; plugin for the FireFox browser. After you have successfully logged into the application, click on the &#8220;Cookies&#8221; drop down and then &#8220;View Cookie Information&#8221;.</p>
<p>Note: In this example, I having both the username and password being saved unencrypted in the browsers cookies. You will need to be the judge of whether or not this is going to work for you, and either use or modify the code according to your needs. In a future tutorial we will talk about encryption.</p>
<p><img src="http://blog.anaara.com/wp-content/uploads/2011/02/CLB3-2-300x140.gif" alt="Flex 4 - Customizing a Login Box using FB4, PHP and mySQL - Viewing Cookies" width="300" height="140" /></p>
<p><strong>Getting the Cookie</strong></p>
<p>Now that you are successfully setting the cookie, you need to implement the functionality to retrieve it. The first thing you need to do is commit the php code that you will be calling from Flex. The job of the php service is to send the username and password that you have stored as cookies so that Flex can insert the respective values in the username and password fields of the login screen.</p>
<p>getCookie.php</p>
<pre>  &lt;?php

 if($_COOKIE["username"])
  {
  print "&lt;storedCookie&gt;true&lt;/storedCookie&gt;";

  print "&lt;creds&gt;
  &lt;username&gt;".$_COOKIE["username"]."&lt;/username&gt;
  &lt;password&gt;".$_COOKIE["password"]."&lt;/password&gt;
  &lt;/creds&gt;";
  }
  else
  {
  print "&lt;storedCookie&gt;false&lt;/storedCookie&gt;";
  }

?&gt;</pre>
<p>Next you will make the change in FB4 to call getCookie.php and then intercept the variables being passed back and put them to work.</p>
<p>1. Write the HTTPService <code>&lt;s:HTTPService id="getCookie" result="getCookie_resultHandler(event)" method="POST" url="getCookie.php"/&gt;</code> and place it in the Declarations tag.</p>
<p>2. Write a function to call the HTTPService you just created.</p>
<pre>  private function init():void
  {
  getCookie.send();
  }</pre>
<p>3. Initiate the function adding the applicationComplete event to the opening application tag: <code>applicationComplete="init()"</code></p>
<p>4. Write a function for the result handler of the HTTPService.</p>
<pre>  protected function getCookie_resultHandler(event:ResultEvent):void
  {
  if(event.result.storedCookie == true)
  {
  cookieAction = true;
  username.text = event.result.creds.username;
  password.text = event.result.creds.password;
  }
  else
  {
  cookieAction == false;
  }
  }</pre>
<p>This says: if the getCookie.php sends back a value of true, that means there was a stored cookie, then go ahead and mark the CheckBox on the login screen and fill out the username and password TextInput fields with the username and password returned from the cookie. Otherwise, just set cookieAction to false.</p>
<p>5. Change the selected property of the CheckBox so that it will be either checked or not checked based on the <code>getCookie_resultHandler</code>.</p>
<p>Change From:</p>
<p><code>&lt;s:CheckBox x="10" y="101" label="Remember Me" id="setCookie" includeIn="loggedOut"/&gt;</code></p>
<p>Change To:</p>
<p><code>&lt;s:CheckBox x="10" y="101" label="Remember Me" id="setCookie" selected="{cookieAction}" includeIn="loggedOut"/&gt;</code></p>
<p>That&#8217;s it. Go ahead and test the functionality, and you should see that when the &#8220;Remember Me&#8221; check box is marked, that it will store a cookie with your login information, and when you reload the application it will fill out the username, password and mark the &#8220;Remember me&#8221; box. If you then remove the mark from the CheckBox, it will delete the stored cookies and the next time you reload the application, your login information will not be stored.</p>
<p>Your application should look like this:</p>
<pre>  &lt;?xml version="1.0" encoding="utf-8"?&gt;
  &lt;s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"
  xmlns:s="library://ns.adobe.com/flex/spark"
  xmlns:mx="library://ns.adobe.com/flex/mx"
  applicationComplete="init()"
  minWidth="955" minHeight="600" xmlns:valueObjects="valueObjects.*"
  xmlns:usersservice="services.usersservice.*"&gt;
  &lt;fx:Script&gt;
  &lt;![CDATA[
  import mx.controls.Alert;
  import mx.rpc.events.ResultEvent;

  private var userid:int;
  private var usertype:String;

  [Bindable]
  private var cookieAction:Boolean;

  protected function saveBtn_clickHandler(event:MouseEvent):void
  {
  var users2:Users = new Users();
  users2.username = usernameTextInput2.text;
  users2.email = emailTextInput2.text;
  users2.password = passwordTextInput2.text;
  users2.user_type = "user";

  createUsersResult.token = usersService.createUsers(users2);
  createUsersResult.token = usersService.commit();
  currentState = 'loggedOut';
  }

  private function checkLogin(event:ResultEvent):void
  {
  userid = event.result.loginsuccess;
  trace (userid);
  usertype = event.result.usertype;
  trace (usertype);
  cookieAction = event.result.usertype;
  trace (cookieAction);
  if (userid != 0)
  {
  currentState = usertype;
  }
  else
  {
  mx.controls.Alert.show('Invalid username/password');
  }
  }

  protected function createUsersResult_resultHandler(event:ResultEvent):void
  {
  mx.controls.Alert.show('Thank you for registering. You may login now!');
  currentState = "loggedOut";
  }

  private function init():void
  {
  getCookie.send();
  }

 protected function getCookie_resultHandler(event:ResultEvent):void
  {
  if(event.result.storedCookie == true)
  {
  cookieAction = true;
  username.text = event.result.creds.username;
  password.text = event.result.creds.password;
  }
  else
  {
  cookieAction == false;
  }
  }

  ]]&gt;
  &lt;/fx:Script&gt;
  &lt;s:states&gt;
  &lt;s:State name="loggedOut"/&gt;
  &lt;s:State name="forgotPW"/&gt;
  &lt;s:State name="register"/&gt;
  &lt;s:State name="user"/&gt;
  &lt;s:State name="admin"/&gt;
  &lt;/s:states&gt;
  &lt;fx:Declarations&gt;
  &lt;s:HTTPService id="login_user" result="checkLogin(event)" showBusyCursor="true" method="POST"
  url="login.php" useProxy="false"&gt;
  &lt;s:request xmlns=""&gt;
  &lt;username&gt;
  {username.text}
  &lt;/username&gt;
  &lt;password&gt;
  {password.text}
  &lt;/password&gt;
  &lt;logincookie&gt;
  {setCookie.selected}
  &lt;/logincookie&gt;
  &lt;/s:request&gt;
  &lt;/s:HTTPService&gt;

  &lt;s:HTTPService id="getCookie" result="getCookie_resultHandler(event)" method="POST" url="getCookie.php"/&gt;

  &lt;valueObjects:Users id="users"/&gt;
  &lt;usersservice:UsersService id="usersService" fault="Alert.show(event.fault.faultString + '\n' + event.fault.faultDetail)" showBusyCursor="true"/&gt;
  &lt;s:CallResponder id="createUsersResult" result="createUsersResult_resultHandler(event)"/&gt;
  &lt;!-- Place non-visual elements (e.g., services, value objects) here --&gt;
  &lt;/fx:Declarations&gt;
  &lt;s:Panel width="250" height="200" title="Flex 4 Login Box" horizontalCenter="0" verticalCenter="0"&gt;
  &lt;s:Label x="10" y="18" text="Username" includeIn="loggedOut"/&gt;
  &lt;s:TextInput x="110" y="10" id="username" includeIn="loggedOut"/&gt;
  &lt;s:Label x="12" y="47" text="Password" includeIn="loggedOut"/&gt;
  &lt;s:TextInput x="110" y="40" id="password" displayAsPassword="true" includeIn="loggedOut"/&gt;
  &lt;s:Button x="10" y="72" label="Login" click="login_user.send();" includeIn="loggedOut"/&gt;
  &lt;s:Button x="120" y="72" label="Forgot Login Info?" click="currentState='forgotPW'" includeIn="loggedOut"/&gt;
  &lt;s:CheckBox x="10" y="101" label="Remember Me" id="setCookie" selected="{cookieAction}" includeIn="loggedOut"/&gt;
  &lt;s:Label x="195" y="103" text="Sign Up" click="currentState='register'" includeIn="loggedOut"/&gt;

  &lt;s:Label x="10" y="46" text="Email:" includeIn="forgotPW"/&gt;
  &lt;s:TextInput x="110" y="39" id="email_to" includeIn="forgotPW"/&gt;
  &lt;s:Button x="10" y="72" label="Get Login Info" includeIn="forgotPW"/&gt;
  &lt;s:Button x="168" y="72" label="&amp;lt;&amp;lt; Login" click="currentState='loggedOut'" includeIn="forgotPW"/&gt;

  &lt;s:Label x="10" y="31" text="Username:" includeIn="register"/&gt;
  &lt;s:TextInput x="110" y="24" id="usernameTextInput2" text="{users.username}" includeIn="register"/&gt;
  &lt;s:Label x="10" y="61" text="Email:" includeIn="register"/&gt;
  &lt;s:TextInput x="110" y="54" id="emailTextInput2" text="{users.email}" includeIn="register"/&gt;
  &lt;s:Label x="10" y="91" text="Password:" includeIn="register"/&gt;
  &lt;s:TextInput x="110" y="84" id="passwordTextInput2" text="{users.password}" displayAsPassword="true" includeIn="register"/&gt;
  &lt;s:Button x="10" y="118" label="Save" id="saveBtn" click="saveBtn_clickHandler(event)" includeIn="register"/&gt;
  &lt;s:Button x="168" y="118" label="&amp;lt;&amp;lt; click=currentState='loggedOut'" Login" includeIn="register"/&gt;

  &lt;s:Label x="10" y="10" text="Welcome User" includeIn="user"/&gt;
  &lt;s:Button x="10" y="30" label="Log Out" click="currentState='loggedOut'" includeIn="user"/&gt;

  &lt;s:Label x="10" y="10" text="Welcome Admin" includeIn="admin"/&gt;
  &lt;s:Button x="10" y="30" label="Admin Log Out" click="currentState='loggedOut'" includeIn="admin"/&gt;
  &lt;/s:Panel&gt;
  &lt;/s:Application&gt;</pre>
<div><span style="line-height: 24px;font-size: 16px;color: #0066cc"><br />
</span></div>
]]></content:encoded>
			<wfw:commentRss>http://blog.anaara.com/archives/366/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Creating a Login Box with FB4, PHP and mySQL &#8211; Part 2</title>
		<link>http://blog.anaara.com/archives/363</link>
		<comments>http://blog.anaara.com/archives/363#comments</comments>
		<pubDate>Mon, 21 Feb 2011 13:53:30 +0000</pubDate>
		<dc:creator>Dan Orlando</dc:creator>
				<category><![CDATA[ActionScript]]></category>
		<category><![CDATA[Adobe]]></category>
		<category><![CDATA[Flash]]></category>
		<category><![CDATA[Flex]]></category>
		<category><![CDATA[Flex 4]]></category>
		<category><![CDATA[php]]></category>
		<category><![CDATA[RIA]]></category>

		<guid isPermaLink="false">http://blog.anaara.com/?p=363</guid>
		<description><![CDATA[Welcome back for part 2 of building a login box using Flash Builder 4, PHP, and mySQL. In this tutorial we will connect the application to the database using FB4&#8242;s built-in data-centric development tools using PHP. What we are looking &#8230; <a href="http://blog.anaara.com/archives/363">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>Welcome back for part 2 of building a login box using Flash Builder 4, PHP, and mySQL. In this tutorial we will connect the application to the database using FB4&#8242;s built-in data-centric development tools using PHP. What we are looking to accomplish is:</p>
<p>1. Create a User in the database using the registration form</p>
<p>2. Connect the login form to the database to check credentials before allowing login</p>
<p>3. Provide custom alerts for the application to communicate with the user</p>
<p>To get started, the first thing you&#8217;ll need to do is get the app to communicate with the MySQL database using FB4&#8242;s built in data-centric development features. By entering a few basic paramters, FB4 will generate the middle-tier (PHP) and Actionscript code for get, create, delete, and edit to make this communication possible. However, the one we&#8217;ll focus on in this tutorial is create. FB4 has many cool features built right in, which make data connection a breeze. If you have not had the opportunity to get familiar with the DCD features of Flash Builder 4, I encourage you to read my entry titled Data Centric Development with Flash Builder 4 &#8211; <a href="http://blog.anaara.com/archives/295">http://blog.anaara.com/archives/295</a>.</p>
<p><strong>Creating the Database</strong></p>
<p>Lets get started creating a new database for the application by logging into your local server (eg. MAMP) or your hosting provider&#8217;s server control panel. Assuming that you have phpMyAdmin available to use and a database administration interface, login and create a new database. Click on the Query tab and copy and paste the SQL statement shown below into the query box. Once you click &#8220;Go&#8221; you will have created a table called &#8220;users&#8221; in your database and have two records.</p>
<pre>  CREATE TABLE `users` (
  `id` int(8) NOT NULL AUTO_INCREMENT,
  `username` varchar(20) DEFAULT NULL,
  `email` varchar(100) DEFAULT NULL,
  `password` varchar(20) DEFAULT NULL,
  `user_type` varchar(20) DEFAULT NULL,
  PRIMARY KEY (`id`)
  ) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=3 ;

--
  -- Dumping data for table `users`
  --

INSERT INTO `users` VALUES(1, 'testUser', 'testuser@email.com', '123456', 'user');
INSERT INTO `users` VALUES(2, 'testAdmin', 'testadmin@email.com', '098765', 'admin');</pre>
<p>Now, go back to Flash Builder, select the Data/Services tab, and click &#8220;Connect to Data/Services&#8221;. Choose &#8220;PHP&#8221; and click &#8220;next&#8221;. Now choose the link labeled &#8220;click here to generate a sample&#8221;. It will then prompt you to install ZEND AMF if you have not already done so.</p>
<p>Once Zend has installed successfully you will tell FB4 how to connect with your database. This information will be used to generate the PHP code. After you enter the information, hit &#8220;Next&#8221;, and then &#8220;OK&#8221; on the Security Warning alert box.</p>
<p>Note: if you are using MAMP, go to the MAMP startup page to get your settings.</p>
<p>Once you have completed these steps, the PHP page that was generated by FB4 will be brought up in your default PHP or text editor.</p>
<p>Everything that you need to be able to connect to the database for the registration page has been completed for you now by Flash Builder, but you still have some work to do. Switch over to design view and select the &#8220;register&#8221; state if you are not there already. Once you are there, click on the &#8220;Data/Service&#8221; Tab and follow the steps below.</p>
<p>1. Highlight <code>createUsers(item:Users):int</code></p>
<p>2. Click the &#8220;Generate Form…&#8221; button. This button is located at the far right of the &#8220;Data/Services&#8221; tab.</p>
<p>3. When the &#8220;Generate Form&#8221; window opens, uncheck the &#8220;Form for return type&#8221; check box and click &#8220;Next&#8221;</p>
<p>4. In the properties column click the arrow to expand the item</p>
<p>5. What you will see is a list of what FB4 is going to create for you in the generated &#8220;Create&#8221; form. For this example, you are not interested in &#8220;id&#8221; because it is set to auto-increment in the database, and &#8220;user_type&#8221; because you are going to have that auto inserted by flex later. So, go ahead and uncheck those two boxes.</p>
<p>6. Click &#8220;Finish&#8221;</p>
<p>You now have a choice here: 1) You can delete the form that you created in the first section as well as the &#8220;Save&#8221; button and drag the generated form into the Panel (which is probably the easiest), or 2) you can use that information to make what you originally created on the canvas work and then delete the generated form and button. The choice is up to you, but in this tutorial, I will do it the second way because it allows us to better inspect what is being created by FB4.</p>
<p>From here you are going to switch over to source view so that you can make the next set of changes.</p>
<p><strong>Editing the Create Form</strong></p>
<p>The goal here is to combine TextInput field properties using the &#8220;id&#8221; and &#8220;text&#8221; properties of the generated code and the includeIn property of what you originally created. As far as the button goes, you&#8217;ll want to keep the id and click event from the generated button and add it to our button. Also, when you make the change, also change the button id and click event to something more meaningful such as <code>id="saveBtn"</code> and <code>click="saveBtn_clickHandler(event)"</code>.</p>
<p>The combination of the two should look something like this:</p>
<pre>  &lt;s:Label x="10" y="31" text="Username:" includeIn="register"/&gt;
  &lt;s:TextInput x="110" y="24" id="usernameTextInput2" text="{users.username}" includeIn="register"/&gt;
  &lt;s:Label x="10" y="61" text="Email:" includeIn="register"/&gt;
  &lt;s:TextInput x="110" y="54" id="emailTextInput2" text="{users.email}" includeIn="register"/&gt;
  &lt;s:Label x="10" y="91" text="Password:" displayAsPassword="true" includeIn="register"/&gt;
  &lt;s:TextInput x="110" y="84" id="passwordTextInput2" text="{users.password}" includeIn="register"/&gt;
  &lt;s:Button x="10" y="118" label="Save" id="saveBtn" click="saveBtn_clickHandler(event)" includeIn="register"/&gt;
  &lt;s:Button x="168" y="118" label="&amp;lt;&amp;lt; Login" click="currentState='loggedOut'" includeIn="register"/&gt;</pre>
<p>Now we need to add additional code to the saveBtn_clickhandler that will commit the new record to the database. To do this you need to add <code>createUsersResult.token = usersService.commit();</code> to the end of the function.</p>
<p><strong>User Alert</strong></p>
<p>Users like to know what is going on rather than guessing, so it is your job as the developer to tell them that their record was added to the database successfully or not. To do this, you will listen for confirmation from the server side, and then show a confirmation message via an Alert box before directing them to the login page. As you may have noticed, FB4 has already added <code>import mx.controls.Alert;</code>, the import statement for Alerts, otherwise you would have to call it manually.</p>
<p>It is now time to place a result event in the call responder associated with create, which for us is <code>&lt;s:CallResponder id="createUsersResult"/&gt;</code>. To do this you change it to <code>&lt;s:CallResponder id="createUsersResult" result="createUsersResult_resultHandler(event)"/&gt;</code>.</p>
<p>What&#8217;s cool here is that when you start to type &#8220;result&#8221; in the CallResponder tag, FB4&#8242;s autocomplete will not only find &#8220;result&#8221; but will also create the result handler for you if you click enter again after it shows you the option for &#8220;Generate Result Handler&#8221;. After doing so you will see a new function was created that is ready for you to fill in the function&#8217;s body.  This is where you will tell it to show the confirmation and forward the user to the loggedOut state.</p>
<p>Change From:</p>
<pre>protected function createUsersResult_resultHandler(event:ResultEvent):void
  {
  // TODO Auto-generated method stub
  }</pre>
<p>Change To:</p>
<pre>protected function createUsersResult_resultHandler(event:ResultEvent):void
  {
  mx.controls.Alert.show('Thank you for registering. You may login now!');
  currentState = "loggedOut";
  }</pre>
<p>Before we wrap up this functionality, there is one last task to complete. You need to specify one additional piece of information to what is being sent to the server when the user clicks &#8220;Save&#8221; that the user doesn&#8217;t get to control, and that is user_type. For that you need to take another look at the saveBtn_clickHandler function and define the user_type. This is done by adding <code>users2.user_type = "user";</code> Place this line of code directly below where the password is defined. The completed function will look like:</p>
<pre>  protected function saveBtn_clickHandler(event:MouseEvent):void
  {
  var users2:Users = new Users();
  users2.username = usernameTextInput2.text;
  users2.email = emailTextInput2.text;
  users2.password = passwordTextInput2.text;
  users2.user_type = "user";

  createUsersResult.token = usersService.createUsers(users2);
  createUsersResult.token = usersService.commit();
  currentState = 'loggedOut';
  }</pre>
<p>It&#8217;s time now to test it out, so go ahead and run the application and create a new user. Then go and look in your database and make sure the data you entered was added correctly, and that the user_type is showing as &#8220;user&#8221;.</p>
<p><a href="http://blog.anaara.com/wp-content/uploads/2011/02/CLB2-1.gif"><img class="alignleft size-full wp-image-383" src="http://blog.anaara.com/wp-content/uploads/2011/02/CLB2-1.gif" alt="Flex 4 - Building a Login Box using FB4, PHP and mySQL - Registration Confirmation Alert" width="279" height="200" /></a></p>
<p><strong>Logging In</strong></p>
<p>Now that you are able to create an account, you will create the ability to use your new account to login. Although you have not actually written any PHP code yet, all that is about to change. You have to tell PHP to ask MySQL to check the credentials being sent and give the thumbs up or thumbs down, and also return the user_type. Knowing the user_type will allow you to direct the person logging in to the proper state depending on if they are an admin or user.</p>
<p>First thing is to save the php file somewhere where the services can be called. On my local machine, the path is Applications/MAMP/htdocs/example12-debug.</p>
<p>Open up your PHP editor and create a new file called login.php. Then paste the following code into that file and save it.</p>
<p>login.php</p>
<pre>&lt;?php

define( "DATABASE_SERVER", "localhost" );
  define( "DATABASE_USERNAME", "root" );
  define( "DATABASE_PASSWORD", "root" );
  define( "DATABASE_NAME", "example12" );

//connect to the database
  $mysql = mysql_connect(DATABASE_SERVER, DATABASE_USERNAME, DATABASE_PASSWORD) or die(mysql_error());

//select the database
  mysql_select_db( DATABASE_NAME );

//These are the variables that Flex is passing to PHP
  $username = mysql_real_escape_string($_POST["username"]);
  $password = mysql_real_escape_string($_POST["password"]);
  $logincookie = mysql_real_escape_string($_POST["logincookie"]);

//Check the credentials
  $query = "SELECT * FROM users WHERE username = '$username' AND password = '$password'";
  $result = mysql_fetch_array(mysql_query($query));

//Output the returned query in XML: If returned false output 0 else output the users id
  $output = "&lt;loginsuccess&gt;";
  if(!$result)
  {
  $output .= "0";
  }else{
  $output .= $result['id'];
  }
  $output .= "&lt;/loginsuccess&gt;";

//Output the User Type
  $usrtyp .= "&lt;usertype&gt;";
  $usrtyp .= $result['user_type'];
  $usrtyp .= "&lt;/usertype&gt;";

//output all the XML

print ($output);
  print ($usrtyp);

?&gt;</pre>
<p>Now with the PHP in place, you can write the client side code that will pass the variables, call the necessary services, and receive the results that are sent back from the server. The steps for this are as follows:</p>
<p>1. Create two new variables to handle the results that will be received back from the server.</p>
<pre>  private var userid:int;
  private var usertype:String;</pre>
<p>2. Write a new function which will be called by the HTTPService telling Flex what to do with the results it receives.</p>
<pre>  private function checkLogin(event:ResultEvent):void
  {
  userid = event.result.loginsuccess;
  usertype = event.result.usertype;
  if (userid != 0)
  {
  currentState = usertype;
  }
  else
  {
  mx.controls.Alert.show('Invalid username/password');
  }
  }</pre>
<p>What this says is: If the server returns a user id that is not 0, then go ahead and set the currentState to what the server returns as the usertype, otherwise show an alert to the user stating &#8220;Invalid username/password.&#8221;</p>
<p>Note: This works because we have conveniently set all users who create an account to &#8220;user&#8221; for the user_type, and when we created the database we set the admin user_type to &#8220;admin&#8221;.</p>
<p>3. We need to write the HTTP Service request. This will call your service and also set the variables which we will be passing to the server.</p>
<pre>  &lt;s:HTTPService id="login_user" result="checkLogin(event)" showBusyCursor="true" method="POST" url="login.php" useProxy="false"&gt;
  &lt;s:request xmlns=""&gt;
  &lt;username&gt;
  {username.text}
  &lt;/username&gt;
  &lt;password&gt;
  {password.text}
  &lt;/password&gt;
  &lt;/s:request&gt;
  &lt;/s:HTTPService&gt;</pre>
<p>There are a couple of important things going on here. First, in the opening tag you can see the id of &#8220;login_user&#8221;, which is how the service will be called by the click event. The result handler is set with <code>result="checkLogin(event)".</code> You also have to declare the type of service call you&#8217;re making, and you are also specifying the location of the file. Secondly, the code directly below that is what passes the username and password values from the TextInput fields, which has the ids of username and password respectively.</p>
<p>4. Last but not least, we need to tell the &#8220;Login&#8221; button to do something different than what it is doing now. Currently, the click event directs us to the &#8220;user&#8221; state, but now we need it to call the HTTPService to kick start the login process.</p>
<p>Change From:</p>
<p><code>&lt;s:Button x="10" y="72" label="Login" click="currentState='user'" includeIn="loggedOut"/&gt;</code></p>
<p>Change To:</p>
<p><code>&lt;s:Button x="10" y="72" label="Login" click="login_user.send();" includeIn="loggedOut"/&gt;</code></p>
<p><a href="http://blog.anaara.com/wp-content/uploads/2011/02/CLB2-2.gif"><img class="alignleft size-full wp-image-385" src="http://blog.anaara.com/wp-content/uploads/2011/02/CLB2-2.gif" alt="Flex 4 - Building a Login Box using FB4, PHP and mySQL - Showing an Invalid Login Alert" width="246" height="200" /></a></p>
<p>And that is it. You should now be able to run and test the application in three ways.</p>
<p>1. Login as user &#8211; Username: testUser / Password: 123456</p>
<p>2. Login as admin &#8211; Username: testAdmin / Password: 098765</p>
<p>3. Login as you &#8211; Choose the username and password which you created previously</p>
<p>4. Get declined &#8211; choose a username and password different from above and different from the one you created previously</p>
<p>You should see that all is in good working order. At this point your application should look similar to the following code:</p>
<pre>  &lt;?xml version="1.0" encoding="utf-8"?&gt;
  &lt;s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"
  xmlns:s="library://ns.adobe.com/flex/spark"
  xmlns:mx="library://ns.adobe.com/flex/mx" minWidth="955" minHeight="600" xmlns:valueObjects="valueObjects.*" xmlns:usersservice="services.usersservice.*"&gt;
  &lt;fx:Script&gt;
  &lt;![CDATA[
  import mx.controls.Alert;
  import mx.rpc.events.ResultEvent;

  private var userid:int;
  private var usertype:String;

  protected function saveBtn_clickHandler(event:MouseEvent):void
  {
  var users2:Users = new Users();
  users2.username = usernameTextInput2.text;
  users2.email = emailTextInput2.text;
  users2.password = passwordTextInput2.text;
  users2.user_type = "user";

  createUsersResult.token = usersService.createUsers(users2);
  createUsersResult.token = usersService.commit();
  currentState = 'loggedOut';
  }

  private function checkLogin(event:ResultEvent):void
  {
  userid = event.result.loginsuccess;
  usertype = event.result.usertype;
  if (userid != 0)
  {
  currentState = usertype;
  }
  else
  {
  mx.controls.Alert.show('Invalid username/password');
  }
  }

  protected function createUsersResult_resultHandler(event:ResultEvent):void
  {
  mx.controls.Alert.show('Thank you for registering. You may login now!');
  currentState = "loggedOut";
  }

 ]]&gt;
  &lt;/fx:Script&gt;
  &lt;s:states&gt;
  &lt;s:State name="loggedOut"/&gt;
  &lt;s:State name="forgotPW"/&gt;
  &lt;s:State name="register"/&gt;
  &lt;s:State name="user"/&gt;
  &lt;s:State name="admin"/&gt;
  &lt;/s:states&gt;
  &lt;fx:Declarations&gt;
  &lt;s:HTTPService id="login_user" result="checkLogin(event)" showBusyCursor="true" method="POST"
  url="login.php" useProxy="false"&gt;
  &lt;s:request xmlns=""&gt;
  &lt;username&gt;
  {username.text}
  &lt;/username&gt;
  &lt;password&gt;
  {password.text}
  &lt;/password&gt;
  &lt;/s:request&gt;
  &lt;/s:HTTPService&gt;

  &lt;valueObjects:Users id="users"/&gt;
  &lt;usersservice:UsersService id="usersService" fault="Alert.show(event.fault.faultString + '\n' + event.fault.faultDetail)" showBusyCursor="true"/&gt;
  &lt;s:CallResponder id="createUsersResult" result="createUsersResult_resultHandler(event)"/&gt;
  &lt;!-- Place non-visual elements (e.g., services, value objects) here --&gt;
  &lt;/fx:Declarations&gt;
  &lt;s:Panel width="250" height="200" title="Flex 4 Login Box" horizontalCenter="0" verticalCenter="0"&gt;
  &lt;s:Label x="10" y="18" text="Username" includeIn="loggedOut"/&gt;
  &lt;s:TextInput x="110" y="10" id="username" includeIn="loggedOut"/&gt;
  &lt;s:Label x="12" y="47" text="Password" includeIn="loggedOut"/&gt;
  &lt;s:TextInput x="110" y="40" id="password" displayAsPassword="true" includeIn="loggedOut"/&gt;
  &lt;s:Button x="10" y="72" label="Login" click="login_user.send();" includeIn="loggedOut"/&gt;
  &lt;s:Button x="120" y="72" label="Forgot Login Info?" click="currentState='forgotPW'" includeIn="loggedOut"/&gt;
  &lt;s:CheckBox x="10" y="101" label="Remember Me" includeIn="loggedOut"/&gt;
  &lt;s:Label x="195" y="103" text="Sign Up" click="currentState='register'" includeIn="loggedOut"/&gt;

  &lt;s:Label x="10" y="46" text="Email:" includeIn="forgotPW"/&gt;
  &lt;s:TextInput x="110" y="39" id="email_to" includeIn="forgotPW"/&gt;
  &lt;s:Button x="10" y="72" label="Get Login Info" includeIn="forgotPW"/&gt;
  &lt;s:Button x="168" y="72" label="&amp;lt;&amp;lt; Login" click="currentState='loggedOut'" includeIn="forgotPW"/&gt;

  &lt;s:Label x="10" y="31" text="Username:" includeIn="register"/&gt;
  &lt;s:TextInput x="110" y="24" id="usernameTextInput2" text="{users.username}" includeIn="register"/&gt;
  &lt;s:Label x="10" y="61" text="Email:" includeIn="register"/&gt;
  &lt;s:TextInput x="110" y="54" id="emailTextInput2" text="{users.email}" includeIn="register"/&gt;
  &lt;s:Label x="10" y="91" text="Password:" includeIn="register"/&gt;
  &lt;s:TextInput x="110" y="84" id="passwordTextInput2" text="{users.password}" displayAsPassword="true" includeIn="register"/&gt;
  &lt;s:Button x="10" y="118" label="Save" id="saveBtn" click="saveBtn_clickHandler(event)" includeIn="register"/&gt;
  &lt;s:Button x="168" y="118" label="&amp;lt;&amp;lt; Login" click="currentState='loggedOut'" includeIn="register"/&gt;

  &lt;s:Label x="10" y="10" text="Welcome User" includeIn="user"/&gt;
  &lt;s:Button x="10" y="30" label="Log Out" click="currentState='loggedOut'" includeIn="user"/&gt;

  &lt;s:Label x="10" y="10" text="Welcome Admin" includeIn="admin"/&gt;
  &lt;s:Button x="10" y="30" label="Admin Log Out" click="currentState='loggedOut'" includeIn="admin"/&gt;
  &lt;/s:Panel&gt;
  &lt;/s:Application&gt;</pre>
<p>TIPS:<br />
If you would like to make sure the correct variables are being passed back from the server to flex use the trace statement. For example, change this part of your checkLogin function:</p>
<p>Change From:</p>
<pre>userid = event.result.loginsuccess;
  usertype = event.result.usertype;</pre>
<p>Change To:</p>
<pre>userid = event.result.loginsuccess;
  trace (userid);
  usertype = event.result.usertype;
  trace (usertype);</pre>
<p>Now when you run your application in debug mode, and look in the FB4 console, you can see what is being returned to you from the server.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.anaara.com/archives/363/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Creating a Login Box with FB4, PHP and mySQL &#8211; Part 1</title>
		<link>http://blog.anaara.com/archives/359</link>
		<comments>http://blog.anaara.com/archives/359#comments</comments>
		<pubDate>Tue, 15 Feb 2011 13:51:00 +0000</pubDate>
		<dc:creator>Dan Orlando</dc:creator>
				<category><![CDATA[ActionScript]]></category>
		<category><![CDATA[Adobe]]></category>
		<category><![CDATA[Flash]]></category>
		<category><![CDATA[Flex]]></category>
		<category><![CDATA[Flex 4]]></category>
		<category><![CDATA[mySQL]]></category>
		<category><![CDATA[php]]></category>
		<category><![CDATA[RIA]]></category>

		<guid isPermaLink="false">http://blog.anaara.com/?p=359</guid>
		<description><![CDATA[Most standalone applications require a login box of some sort. That is why today we will begin our journey into building a login and registration form that will be reusable for many types of applications, or may act as a &#8230; <a href="http://blog.anaara.com/archives/359">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>Most standalone applications require a login box of some sort. That is why today we will begin our journey into building a login and registration form that will be reusable for many types of applications, or may act as a starting point for something more detailed. This will be a multi-part tutorial walking you through the major steps involved. Although each tutorial will be able to stand on its own to learn a particular skill, you can also follow them in order (listed below) and build the application from start to finish.</p>
<p><span style="font-family: Georgia, 'Bitstream Charter', serif;line-height: 24px;font-size: 16px"> </span></p>
<ol>
<li>States and Layout</li>
<li>Connecting to DB and PHP</li>
<li>Setting cookies</li>
<li>Creating the forgot login functionality</li>
<li>Validation &amp; Disable Save Button</li>
<li>No Duplicates in DB when creating new user</li>
<li>Email validation prior to account activation</li>
<li>Password Encryption</li>
<li>Converting the application into a component</li>
</ol>
<p>At this time lets go ahead and get started on the first part, States and Layout. We will begin by creating a new Flex application. I am also going to set the Application Server type as PHP, and set the parameters of my server location. If you have connected to a server before, your settings should be saved and preloaded by FB4 by default. In my case the server settings are as follows:</p>
<p>Web root: /Applications/MAMP/htdocs</p>
<p>Root URL: http://localhost:8888</p>
<p>Note: MAMP is for Mac users and stands for Mac, Apache, mySQL, and PHP. This is a great stack which gives Mac users the ability to run applications locally, and is an easy one click install. There are two versions available, and you can get more information and download the product from their website at http://www.mamp.info.</p>
<p>Now that we have our new Flex application set up, its time to start building. The first thing that we want to know is what functionality is needed, and what states we&#8217;ll need to accomplish the tasks. The easiest way to do this is to write a list or make a drawing that you can use as reference. For this project, my list looks like this:</p>
<p><strong>Functionality:</strong></p>
<ul>
<li> Login to application</li>
<li> Know the difference between user types and send them to the right place when they login</li>
<li>Connect, and commit information to database</li>
<li>Set cookie for login information</li>
<li>Email password if forgotten</li>
<li>Register new users</li>
<li>Check for duplicates in database before creating new entry</li>
<li>Validate user information</li>
<li>Email validation</li>
<li>Password Encryption</li>
<li>Disable save button until the user registration info has been validated</li>
</ul>
<p>Note: We will not be working on all of the functionality in this tutorial, but it is important to know what you would like the end result to be when you start a project so you take everything into account during development.</p>
<p><strong>States:</strong></p>
<p>1. Login</p>
<p>2. Forgot Password</p>
<p>3. Registration</p>
<p>4. Logged in as regular user</p>
<p>5. Logged in as admin</p>
<p>Ok, now that you have a list of tasks that you&#8217;d like to achieve for this app, you&#8217;ll focus on creating the states and laying out the other necessary components. Once you have completed that, you will continue by writing the code needed to make the login box meet the desired functionality from the list above. Since most of the initial layout and state creation can be developed from the design view, go ahead and click on the &#8220;Design&#8221; tab in Flash Builder now.</p>
<p>Creating the Layout Panel</p>
<p>1. Drag a Panel object from the Components tab to the canvas.</p>
<p>2. Type &#8220;Flex 4 Login Box&#8221; into the Title text field in the Properties panel.</p>
<p>3. Click over to source view and set the horizontalCenter and verticalCenter properties to 0 for the Panel.</p>
<pre>  &lt;s:Panel width="250" height="200" title="Flex 4 Login Box" horizontalCenter="0" verticalCenter="0"&gt;</pre>
<p><img src="http://blog.anaara.com/wp-content/uploads/2011/02/CLB1-1.png" alt="Flex 4 Panel Component" width="243" height="200" /></p>
<p><strong>Creating the Login Screen &lt;loggedOut&gt;</strong></p>
<p>On the login screen we want the following components:</p>
<ul>
<li>a &#8220;Username&#8221; TextInput field,</li>
<li>a &#8220;Password&#8221; TextInput field,</li>
<li>a &#8220;Login&#8221; button,</li>
<li>a &#8220;Forgot Login Info?&#8221; button,</li>
<li>a &#8220;Sign Up&#8221; label to link to the registration form, and</li>
<li>a checkbox for the &#8220;Remember Me&#8221; functionality.</li>
</ul>
<p><span style="font-family: Georgia, 'Bitstream Charter', serif;line-height: 24px;font-size: 16px"> To get all the components necessary to achieve this, follow the steps below:</span></p>
<p>1a. Drag two (2) TextInput components and two (2) Label components on top of the Panel. These will be used for the username and password TextInput fields.</p>
<p>1b. Set the id of one of the TextInput fields to &#8220;username&#8221; and the other to &#8220;password&#8221;</p>
<p>1c. Set the text property of one of the Labels to &#8220;Username:&#8221; and the other to &#8220;Password:&#8221;</p>
<p>2a. Drag two (2) button components on top of the Panel.</p>
<p>2b. Set the Label property of one button to &#8220;Login&#8221; and the other to &#8220;Forgot Login Info?&#8221;</p>
<p>3a. Drag a CheckBox component on top of the Panel.</p>
<p>3b. Set the label property to &#8220;Remember Me&#8221;</p>
<p>4a. Drag a Label component on top of the Panel.</p>
<p>4b. Set the text property to &#8220;Sign up&#8221;</p>
<p>5. Format the layout to your liking.</p>
<p><a href="http://blog.anaara.com/wp-content/uploads/2011/02/CLB1-1.png"></a><a href="http://blog.anaara.com/wp-content/uploads/2011/02/CLB1-2.gif"><img class="alignleft size-full wp-image-377" src="http://blog.anaara.com/wp-content/uploads/2011/02/CLB1-2.gif" alt="Flex 4 - Login Box Application - Login Screen" width="253" height="200" /></a></p>
<p><strong>Creating the Forgot Password State &lt;forgotPW&gt;</strong></p>
<p>Until now the only state listed in the states tab is &lt;state1&gt;. In order to change that click the &#8220;New State&#8221; button which is the first button at the top of the &#8220;States&#8221; tab. When you do this a window will open asking you a couple of questions. Set the name to &#8220;forgotPW&#8221;, then click the radio button &#8220;Duplicate of &lt;State1&gt;&#8221;,  leave the &#8220;Set as Start State&#8221; checkbox empty, and click &#8220;OK&#8221; to finish.</p>
<p><a href="http://blog.anaara.com/wp-content/uploads/2011/02/CLB1-3.gif"><img class="alignleft size-full wp-image-376" src="http://blog.anaara.com/wp-content/uploads/2011/02/CLB1-3.gif" alt="Flex 4 - Adding a New State" width="283" height="200" /></a></p>
<p>FB4 will now show you the new design state for forgotPW which will look identical to what you just created. Before we go any further, right click or control click &lt;state1&gt; and click &#8220;Edit&#8221;. Now change the name of the state to &#8220;loggedOut&#8221; and check the box &#8220;Set as Start State&#8221; and click &#8220;OK&#8221;. You should now see two states in the states tab listed.</p>
<p><a href="http://blog.anaara.com/wp-content/uploads/2011/02/CLB1-3b.gif"><img class="alignleft size-medium wp-image-375" src="http://blog.anaara.com/wp-content/uploads/2011/02/CLB1-3b-300x188.gif" alt="Flash Builder 4 - FB4 States Tab showing 2 states" width="300" height="188" /></a></p>
<p>In this state we are going to need an &#8220;Email&#8221; TextInput box, &#8220;Send Login Info&#8221; button, and a &#8220;&lt;&lt; Login&#8221; button to get us back to the login screen. There are two ways to do this, but I chose the way described below based on personal preference.</p>
<p>Delete all components leaving only the Panel and drag the necessary components to the Panel.</p>
<p>Once that is complete change the text input box id property to &#8220;email&#8221;, the label text property to &#8220;Email:&#8221;, and one button&#8217;s label property to &#8220;Send Login Info&#8221; and the other to &#8220;&lt;&lt; Login&#8221;.</p>
<p>Finally, format the layout for the desired look your want. You should now see two states and when you click back and forth between the two, the only similarity is the Panel which is holding the components.</p>
<p><a href="http://blog.anaara.com/wp-content/uploads/2011/02/CLB1-4.gif"><img class="alignleft size-full wp-image-373" src="http://blog.anaara.com/wp-content/uploads/2011/02/CLB1-4.gif" alt="Flex 4 - Building a Login Box using FB4, PHP and mySQL - Forgot Password Screen" width="269" height="200" /></a></p>
<p><strong>Creating the Registration State &lt;register&gt;</strong></p>
<p>Create a new state as you did in the previous step, but this time name it &#8220;register&#8221; and choose to duplicate the logged out state. This state is going to need TextInput boxes for &#8220;Username&#8221;, &#8220;Email&#8221; and &#8220;Password&#8221;, a &#8220;Save&#8221; button, and a &#8220;&lt;&lt; Login&#8221; button. Delete the existing components and drag the needed components to the panel. When you are finished set the ids of the text boxes as follows: &#8220;usernameTextInput&#8221; &#8220;emailTextInput&#8221; and &#8220;passwordTextInput&#8221;. Make sure that your labels match up with the corresponding TextInput field. Finally, set the labels of the buttons to &#8220;Save&#8221; and &#8220;&lt;&lt; Login&#8221;. After you have done this, go ahead and change the formatting to make it look the way you desire.</p>
<p><a href="http://blog.anaara.com/wp-content/uploads/2011/02/CLB1-5.gif"><img class="alignleft size-full wp-image-372" src="http://blog.anaara.com/wp-content/uploads/2011/02/CLB1-5.gif" alt="Flex 4 - Building a Login Box using FB4, PHP and mySQL - Registration Screen" width="269" height="200" /></a></p>
<p>Creating the LoggedIn States &lt;user&gt; and &lt;admin&gt;</p>
<p>To create the logged-in states, follow the same steps as before, but this time set the first new state to &#8220;user&#8221;, the second to &#8220;admin&#8221;, and it doesn&#8217;t matter which state you duplicate. On each of these states we need one button and one label.</p>
<p>On the &#8220;user&#8221; state, set the label text to &#8220;Welcome User&#8221; and the button label set to &#8220;Log Out&#8221;. On the admin state, set the label text to be &#8220;Welcome Administrator&#8221; and the button label to &#8220;Admin Log Out&#8221;.</p>
<p><a href="http://blog.anaara.com/wp-content/uploads/2011/02/CLB1-6a.gif"><img class="alignleft size-full wp-image-371" src="http://blog.anaara.com/wp-content/uploads/2011/02/CLB1-6a.gif" alt="Flex 4 - Building a Login Box using FB4, PHP and mySQL - User Login State" width="270" height="200" /></a><br />
<strong>Formatting and Editing the Code</strong></p>
<p>At this point your application should look something like this:</p>
<pre>  &lt;s:Application xmlns:fx="http://ns.adobe.com/mxml/2009" 

  xmlns:s="library://ns.adobe.com/flex/spark" 

  xmlns:mx="library://ns.adobe.com/flex/mx" minWidth="955" minHeight="600"&gt;

  &lt;s:states&gt;

  &lt;s:State name="loggedOut"/&gt;

  &lt;s:State name="forgotPW"/&gt;

  &lt;s:State name="register"/&gt;

  &lt;s:State name="user"/&gt;

  &lt;s:State name="admin"/&gt;

  &lt;/s:states&gt;

  &lt;fx:Declarations&gt;

  &lt;!-- Place non-visual elements (e.g., services, value objects) here --&gt;

  &lt;/fx:Declarations&gt;

  &lt;s:Panel width="250" height="200" title="Flex 4 Login Box" horizontalCenter="0" verticalCenter="0"&gt;

  &lt;s:Label x="10" y="18" text="Username" includeIn="loggedOut"/&gt;

  &lt;s:TextInput x="110" y="10" id="username" includeIn="loggedOut"/&gt;

  &lt;s:Label x="12" y="47" text="Password" includeIn="loggedOut"/&gt;

  &lt;s:TextInput x="110" y="40" id="password" includeIn="loggedOut"/&gt;

  &lt;s:Button x="10" y="72" label="Login" click="currentState='user'" includeIn="loggedOut"/&gt;

  &lt;s:Button x="120" y="72" label="Forgot Login Info?" click="currentState='forgotPW'" includeIn="loggedOut"/&gt;

  &lt;s:CheckBox x="10" y="101" label="Remember Me" includeIn="loggedOut"/&gt;

  &lt;s:Label x="195" y="103" text="Sign Up" click="currentState='register'" includeIn="loggedOut"/&gt;

  &lt;s:Label x="10" y="46" text="Email:" includeIn="forgotPW"/&gt;

  &lt;s:TextInput x="110" y="39" id="email_to" includeIn="forgotPW"/&gt;

  &lt;s:Button x="10" y="72" label="Get Login Info" includeIn="forgotPW"/&gt;

  &lt;s:Button x="168" y="72" label="&amp;lt;&amp;lt; Login" click="currentState='loggedOut'" includeIn="forgotPW"/&gt;

  &lt;s:Label x="10" y="31" text="Username:" includeIn="register"/&gt;

  &lt;s:TextInput x="110" y="24" id="usernameTextInput" includeIn="register"/&gt;

  &lt;s:Label x="10" y="61" text="Email:" includeIn="register"/&gt;

  &lt;s:TextInput x="110" y="54" id="emailTextInput" includeIn="register"/&gt;

  &lt;s:Label x="10" y="91" text="Password:" includeIn="register"/&gt;

  &lt;s:TextInput x="110" y="84" id="passwordTextInput" includeIn="register"/&gt;

  &lt;s:Button x="10" y="118" label="Save" includeIn="register"/&gt;

  &lt;s:Button x="168" y="118" label="&amp;lt;&amp;lt; Login" includeIn="register"/&gt;

  &lt;s:Label x="10" y="10" text="Welcome User" includeIn="user"/&gt;

  &lt;s:Button x="10" y="30" label="Log Out" click="currentState='loggedOut'" includeIn="user"/&gt;

  &lt;s:Label x="10" y="10" text="Welcome Admin" includeIn="admin"/&gt;

  &lt;s:Button x="10" y="30" label="Admin Log Out" click="currentState='loggedOut'" includeIn="admin"/&gt;

  &lt;/s:Panel&gt;

  &lt;/s:Application&gt;</pre>
<p><strong>Editing the &#8220;loggedOut&#8221; State</strong></p>
<p>Change From:</p>
<p><code>&lt;s:TextInput x="110" y="40" id="password" includeIn="loggedOut"/&gt;</code></p>
<p>Change To:</p>
<p><code>&lt;s:TextInput x="110" y="40" id="password" displayAsPassword="true" includeIn="loggedOut"/&gt;</code></p>
<p>Change From:</p>
<p><code>&lt;s:Button x="10" y="72" label="Login" includeIn="loggedOut"/&gt;</code></p>
<p>Change To:</p>
<p><code>&lt;s:Button x="10" y="72" label="Login" click="currentState='user'" includeIn="loggedOut"/&gt;</code></p>
<p>Change From:</p>
<p><code>&lt;s:Button x="120" y="72" label="Forgot Login Info?" includeIn="loggedOut"/&gt;</code></p>
<p>Change To:</p>
<p><code>&lt;s:Button x="120" y="72" label="Forgot Login Info?" click="currentState='forgotPW'" includeIn="loggedOut"/&gt;</code></p>
<p>Change From:</p>
<p><code>&lt;s:Label x="195" y="103" text="Sign Up" includeIn="loggedOut"/&gt;</code></p>
<p>Change To:</p>
<p><code>&lt;s:Label x="195" y="103" text="Sign Up" click="currentState='register'" includeIn="loggedOut"/&gt;</code></p>
<p><strong>Editing the &#8220;forgotPW&#8221; State</strong></p>
<p>Don&#8217;t make any changes to the &#8220;Get Login Info&#8221; button because that will not take us to another state at this time.</p>
<p>Change From:</p>
<p><code>&lt;s:Button x="168" y="72" label="&amp;lt;&amp;lt; Login" includeIn="forgotPW"/&gt;</code></p>
<p>Change To:</p>
<p><code>&lt;s:Button x="168" y="72" label="&amp;lt;&amp;lt; Login" click="currentState='loggedOut'" includeIn="forgotPW"/&gt;</code></p>
<p><strong>Editing the &#8220;register&#8221; State</strong></p>
<p>Don&#8217;t make any changes to the &#8220;Save&#8221; button because that will not take us to another state at this time.</p>
<p>Change From:</p>
<p>&lt;s:TextInput x=&#8221;110&#8243; y=&#8221;84&#8243; id=&#8221;passwordTextInput&#8221; includeIn=&#8221;register&#8221;/&gt;</p>
<p>Change To:</p>
<p><code>&lt;s:TextInput x="110" y="84" id="passwordTextInput" displayAsPassword="true" includeIn="register"/&gt;&lt;/code</p>
<p>Change From:</p>
<p><code>&lt;s:Button x="168" y="118" label="&amp;lt;&amp;lt; Login" includeIn="register"/&gt;</code></p>
<p>Change To:</p>
<p><code>&lt;s:Button x="168" y="118" label="&amp;lt;&amp;lt; Login" click="currentState='loggedOut'" includeIn="register"/&gt;</code></p>
<p><strong>Editing the "user" and "admin" States</strong></p>
<p>Change From:</p>
<p><code>&lt;s:Button x="10" y="30" label="Log Out" includeIn="user"/&gt;</code></p>
<p>Change To:</p>
<p><code>&lt;s:Button x="10" y="30" label="Log Out" click="currentState='loggedOut'" includeIn="user"/&gt;<br />
</code></p>
<p>Change From:</p>
<p><code>&lt;s:Button x="10" y="30" label="Admin Log Out" includeIn="admin"/&gt;</code></p>
<p>Change To:</p>
<p><code>&lt;s:Button x="10" y="30" label="Log Out" click="currentState='loggedOut'" includeIn="user"/&gt;</code></p>
<p>Now you should have all of the states created, formatted, and edited so that when you run the application you have a working mockup of how it will interact. When you click on the respective buttons, you should be taken from state to state. The only state that you will not be able to enter at this point will be "admin", but we will get to this soon.</p>
<p>In the next tutorial we will take what we have created so far and connect it to a mySQL database using FB4's Data Centric development tools, and a couple of custom PHP scripts. At that point you will have a fully functional login application.</p>
<div><span style="line-height: 24px;font-size: 16px;color: #ff4b33"><br />
</span></div>
]]></content:encoded>
			<wfw:commentRss>http://blog.anaara.com/archives/359/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Data Centric Development with Flash Builder 4 &#8211; Part 2</title>
		<link>http://blog.anaara.com/archives/313</link>
		<comments>http://blog.anaara.com/archives/313#comments</comments>
		<pubDate>Wed, 09 Feb 2011 15:44:24 +0000</pubDate>
		<dc:creator>Dan Orlando</dc:creator>
				<category><![CDATA[ActionScript]]></category>
		<category><![CDATA[Adobe]]></category>
		<category><![CDATA[Flash]]></category>
		<category><![CDATA[Flex]]></category>
		<category><![CDATA[Flex 4]]></category>
		<category><![CDATA[RIA]]></category>
		<category><![CDATA[flash]]></category>
		<category><![CDATA[php]]></category>
		<category><![CDATA[software]]></category>

		<guid isPermaLink="false">http://blog.anaara.com/?p=313</guid>
		<description><![CDATA[In Part 1 of this entry, you created a working application that allows you to populate a DataGrid using PHP and MySQL. You then added the ability to create, delete, and edit the information in the database. Here is what &#8230; <a href="http://blog.anaara.com/archives/313">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>In Part 1 of this entry, you created a working application that allows you to populate a DataGrid using PHP and MySQL. You then added the ability to create, delete, and edit the information in the database. Here is what it currently looks like:</p>
<p><a href="http://blog.anaara.com/wp-content/uploads/2011/01/DCD2-pic1-small.png"><img class="alignleft size-medium wp-image-341" src="http://blog.anaara.com/wp-content/uploads/2011/01/DCD2-pic1-small-300x135.png" alt="" width="300" height="135" /></a></p>
<p>As you can see, although you created a working application, the look and feel of the application is in some serious need of work in terms of usability. With that said, lets get to work.</p>
<p><strong>Cleaning Up the Create Functionality</strong></p>
<p>First, we will start with the create functionality and remove all it&#8217;s related components that are not needed. You are going to make the workflow such that information is added to a record after it has been created . To do this, you will remove the two associated text input boxes, leaving us with only the Create button. This is easy enough to do in design view, so take advantage of it if you prefer it over source view. After you delete the two TextInput boxes that the application was calling for in the create function, you need to go back change the <code>button_clickHandler</code> function.</p>
<p>Change From</p>
<pre>protected function button_clickHandler(event:MouseEvent):void
  {
    var person2:Person = new Person();
    person2.id = parseInt(idTextInput.text);
    person2.name = nameTextInput.text;

    createPersonResult2.token = personService.createPerson(person2);
  }</pre>
<p>Change To</p>
<pre>protected function button_clickHandler(event:MouseEvent):void
  {
    var person2:Person = new Person();

    createPersonResult2.token = personService.createPerson(person2);
  }</pre>
<p>Now save, build, and run the application.</p>
<p><a href="http://blog.anaara.com/wp-content/uploads/2011/01/DCD2-pic2-small.png"><img class="alignleft size-medium wp-image-343" src="http://blog.anaara.com/wp-content/uploads/2011/01/DCD2-pic2-small-300x169.png" alt="" width="300" height="169" /></a></p>
<p><strong>Cleaning Up the Delete Functionality</strong><br />
Instead of deleting a record by typing the record&#8217;s unique identifier into a text input, you&#8217;re going to have the application delete the person based on what row is  selected in the DataGrid. To do this, you&#8217;ll first need to know the following:</p>
<ol>
<li> the string id assigned to your DataGrid, and</li>
<li>the name given to the primary key/unique identifier field in the database.</li>
</ol>
<p>For this app, the id of the DataGrid is &#8220;dataGrid&#8221; and the name of the field we are using in our database is &#8220;id&#8221;.</p>
<p>The function called when the delete button is clicked is <code>button3_clickHandler</code>, and upon further investigation of the function you&#8217;ll see that <code>deletePersonResult.token = personService.deletePerson(parseInt(itemIDTextInput2.text));</code> is what makes the magic happen. But, since you are deleting the <code>(itemIDTextInput2.text)</code>, the function will no longer work and throw an error. This is because a slight modification is needed, which will tell Flex that we want to delete what is selected on the DataGrid<code>.</code></p>
<p><code> </code></p>
<p><code>Change From:</code></p>
<pre>deletePersonResult.token = personService.deletePerson(parseInt(itemIDTextInput2.text));</pre>
<p>Change To:</p>
<pre>deletePersonResult.token = personService.deletePerson(dataGrid.selectedItem.id);</pre>
<p>Go ahead and delete the text input box associated with delete, then save, build, and run the application.</p>
<p><a href="http://blog.anaara.com/wp-content/uploads/2011/01/DCD2-pic3-small.png"><img class="alignleft size-medium wp-image-345" src="http://blog.anaara.com/wp-content/uploads/2011/01/DCD2-pic3-small-300x160.png" alt="" width="300" height="160" /></a></p>
<p><strong>Cleaning Up the Edit Functionality</strong><br />
Next, lets look at the edit functionality, which also includes several components that aren&#8217;t necessary.  We are going to makes changes to edit it in two parts so that you can have it look and work the way you want based on your application:<br />
A. If you want to keep the text boxes for editing<br />
B. If you want to edit directly within the dataGrid.</p>
<p>Part A:<br />
We need to find out what function is being called by the &#8220;getPerson&#8221; button. By looking at the code we can tell that it is <code>button_clickHandler(event)</code>. Once we have this information you are going to go ahead and delete both the button and text box associated with getPerson. Now you will make a similar modification to the one you did with the delete functionality so that you can populate and edit information based on the selection in the DataGrid.</p>
<p>Change From:</p>
<pre>protected function button_clickHandler(event:MouseEvent):void
  {
    getPersonByIDResult.token = personService.getPersonByID(parseInt(itemIDTextInput.text));
  }</pre>
<p>Change To:</p>
<pre>protected function button_clickHandler(event:MouseEvent):void
  {
    getPersonByIDResult.token = personService.getPersonByID(dataGrid.selectedItem.id);
  }</pre>
<p>Since we have deleted the &#8220;getPerson&#8221; button, you also need a way for the function to be called that will populate your edit text boxes. To do this, you will add the following click handler to the DataGrid  <code>click="button_clickHandler(event)"</code></p>
<p>The opening DataGrid tag should now look like this:</p>
<pre>&lt;mx:DataGrid x="10" y="10" id="dataGrid"
	creationComplete="dataGrid_creationCompleteHandler(event)"
	dataProvider="{getAllPersonResult.lastResult}"
	click="button_clickHandler(event)"&gt;</pre>
<p>Save, build, and run the application now. You can now switch back to design view and slide the components around the canvas to achieve your desired look. If you would like to condense the application even further by editing it directly in the  DataGrid, continue to part B.</p>
<p><a href="http://blog.anaara.com/wp-content/uploads/2011/01/DCD2-pic4-small.png"><img class="alignleft size-medium wp-image-347" src="http://blog.anaara.com/wp-content/uploads/2011/01/DCD2-pic4-small-300x155.png" alt="" width="300" height="155" /></a></p>
<p>Part B:<br />
In order to make changes within the DataGrid, you need to set it to editable by setting editable to &#8220;true&#8221;. In this particular situation, you don&#8217;t want both fields to be editable, so you will set editable to &#8220;false&#8221; for the id column, as seen below:<br />
<code><br />
&lt;mx:DataGrid x="10" y="10" id="dataGrid"<br />
creationComplete="dataGrid_creationCompleteHandler(event)"<br />
dataProvider="{getAllPersonResult.lastResult}"<br />
click="button_clickHandler(event)"<br />
editable="true"&gt;<br />
&lt;mx:columns&gt;<br />
&lt;mx:DataGridColumn headerText="id" dataField="id" editable="false"/&gt;<br />
&lt;mx:DataGridColumn headerText="name" dataField="name"/&gt;<br />
&lt;/mx:columns&gt;<br />
&lt;/mx:DataGrid&gt;<br />
</code><br />
Go ahead and run the application again now and you will see that the name column is editable when clicked on, and the id field is not. Also note that right now it will change the information in the edit screen, but unless you click &#8220;Submit&#8221;, your changes will not be stored in the database.</p>
<p>To change this you will have the DataGrid make the call to commit on the FocusOut event. At this time go ahead and delete the &#8220;Edit Screen&#8221; form.</p>
<p>After the DataGrid&#8217;s opening tag, you need to change the click handler from:<br />
<code>click="button_clickHandler(event)"</code><br />
To:<br />
<code>focusOut="button2_clickHandler(event)"</code><br />
Then change the event type from <code>MouseEvent</code> to <code>Event</code> and tell it to stop looking for the text boxes you deleted or it will throw errors. So the new function will look like:</p>
<pre>protected function button2_clickHandler(event:Event):void
  {
    updatePersonResult.token = personService.commit();
  }</pre>
<p>Now save, test and run your new application. You will find the same functionality but in a much cleaner package. And in the spirit of keeping things clean, you can remove the function calling <code>getPersonByID</code>.</p>
<pre>protected function button_clickHandler(event:MouseEvent):void
  {
    getPersonByIDResult.token = personService.getPersonByID(dataGrid.selectedItem.id);
  }</pre>
<p><a href="http://blog.anaara.com/wp-content/uploads/2011/01/DCD2-pic5-small.png"><img class="alignleft size-full wp-image-349" src="http://blog.anaara.com/wp-content/uploads/2011/01/DCD2-pic5-small-e1296541716366.png" alt="" width="197" height="196" /></a></p>
<p>Thats it… Hope you enjoyed this turorial!</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.anaara.com/archives/313/feed</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Data Centric Development with Flash Builder 4, Part 1</title>
		<link>http://blog.anaara.com/archives/295</link>
		<comments>http://blog.anaara.com/archives/295#comments</comments>
		<pubDate>Mon, 07 Feb 2011 14:30:29 +0000</pubDate>
		<dc:creator>Dan Orlando</dc:creator>
				<category><![CDATA[ActionScript]]></category>
		<category><![CDATA[Adobe]]></category>
		<category><![CDATA[Flash]]></category>
		<category><![CDATA[Flex]]></category>
		<category><![CDATA[Flex 4]]></category>
		<category><![CDATA[RIA]]></category>
		<category><![CDATA[flash]]></category>
		<category><![CDATA[php]]></category>
		<category><![CDATA[software]]></category>

		<guid isPermaLink="false">http://blog.anaara.com/?p=295</guid>
		<description><![CDATA[I&#8217;ve been helping a friend of mine learn Flex for the past month or so and I decided to write up a blog post on something we worked on together over the weekend &#8211; using Flash Builder 4 to connect &#8230; <a href="http://blog.anaara.com/archives/295">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>I&#8217;ve been helping a friend of mine learn Flex for the past month or so and I decided to write up a blog post on something we worked on together over the weekend &#8211; using Flash Builder 4 to connect a flex application to a mySQL database using PHP. Yea, ok, so what. There&#8217;s a million tutorials out there on the same thing. BUT &#8211; the problem is that there aren&#8217;t that many Flex developers that know PHP well enough to be able to adapt what they learn from a tutorial on the subject to their specific requirement. So we&#8217;re going to do things a little differently here. I&#8217;m going to show you how to accomplish this without ever having to look at a single line of PHP code!</p>
<p>Considering how much effort the Flash Builder 4 development team put into the data centric development capabilities of FB4, it is surprising to find that there aren&#8217;t too many tutorials and blog entries that focus on how to utilize these features. With that in mind, we will use FB4’s build in data centric capabilities to make the connection to a mySQL database from design view and add CRUD capabilities to an application. After that, we will dive into the source view to enhance the usability and functionality. Since this is going to be a fairly lengthy one, it will be broken into three separate entries.</p>
<p>For the first entry, you&#8217;ll create the connection to the database and get your CRUD services working.</p>
<p>Start off by creating a new Flex project. When you create the project, be sure to choose PHP for the application server type. You will then have to choose your server location. If you have done so for previous projects, it should be saved in there by default. I am using MAMP so my setup is as follows:</p>
<p>Web root: /Applications/MAMP/htdocs<br />
Root URL: http://localhost:8888</p>
<p><a href="http://blog.anaara.com/wp-content/uploads/2011/01/DCD1-pic1-small.png"><img class="alignleft size-full wp-image-332" src="http://blog.anaara.com/wp-content/uploads/2011/01/DCD1-pic1-small.png" alt="" width="180" height="200" /></a></p>
<p>Once you have it filled out with the correct values, validate your configuration, choose your output folder, and click finish. This will create and launch your new Flex project.</p>
<p><strong>Creating the Database</strong><br />
Now create a new database to use for the application from your hosting provider&#8217;s server control panel. Assuming you have phpMyAdmin available to use as a database administration interface, login and select the database you just created. Then click on the Query tab and paste the following SQL in the query box to create a table and some data.</p>
<pre>CREATE TABLE `person` (
`id` int(8) NOT NULL AUTO_INCREMENT,
`name` varchar(25) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=3 ;

--
-- Dumping data for table `person`
--

INSERT INTO `person` VALUES(1, 'John');
INSERT INTO `person` VALUES(2, 'Bob');</pre>
<p>Now, go back to Flash Builder, select the Data/Services tab, and click &#8220;Connect to Data/Services&#8221;. Choose &#8220;PHP&#8221; and click &#8220;next&#8221;. Now choose the link labeled &#8220;click here to generate a sample&#8221;. It will then prompt you to install ZEND AMF if you have not already done so.</p>
<p>Once Zend has installed successfully you will tell FB4 how to connect with your database. This information will be used to generate the PHP code. After you enter the information, hit &#8220;Next&#8221;, and then &#8220;OK&#8221; on the Security Warning alert box.</p>
<p><a href="http://blog.anaara.com/wp-content/uploads/2011/01/DCD1-pic2-small.png"><img class="alignleft size-full wp-image-334" src="http://blog.anaara.com/wp-content/uploads/2011/01/DCD1-pic2-small.png" alt="" width="182" height="200" /></a></p>
<p><em>Note: if you are using MAMP, go to the MAMP startup page to get your settings.</em></p>
<p>Once you have completed these steps, the PHP page that was generated by FB4 will be brought up in the default editor.</p>
<p><strong>Populating the DataGrid</strong><br />
Step 1. Drag a <code>DataGrid</code> component to the canvas from the Components tab.</p>
<p>Step 2.  Drag <code>getAllPerson():Person[]</code> from the Design/Services tab directly on top of your DataGrid.</p>
<p>Step 3. Save and run your application for the first time.</p>
<p><a href="http://blog.anaara.com/wp-content/uploads/2011/01/DCD1-pic3.png"><img class="alignleft size-full wp-image-335" src="http://blog.anaara.com/wp-content/uploads/2011/01/DCD1-pic3.png" alt="" width="211" height="181" /></a></p>
<p>You should find that the DataGrid is now populated with the information from the database. This is great start, but in most cases completely useless, so lets add the ability create, delete and edit the data base from the application.</p>
<p><strong>Editing the Database</strong><br />
Step 1. From the Data/Services tab click and highlight <code>updatePerson(item:person):void</code> and click on the &#8220;Generate Form&#8221; button.</p>
<p>Note: The Generate Form button is the last button on the right in the top right of the Data/Services tab.</p>
<p>Step 2. A window will open asking you to edit any of the default parameters. You don’t need to change any of the settings, but it is a good idea to take a look around and get a familiar with the dialog boxes because you can edit these parameters later for additional functionality.</p>
<p>Step 3. Click &#8220;Finish&#8221;</p>
<p>Clicking finish generates two forms on the canvas. The first allows you to call data from the database by the id field of the Persons table in the database, and second allowing you to edit your selection. The forms may need to be moved around the canvas so that they do not overlap each other.</p>
<p>Step 4. Save and run the application.</p>
<p><a href="http://blog.anaara.com/wp-content/uploads/2011/01/DCD1-pic4-small.png"><img class="alignleft size-medium wp-image-337" src="http://blog.anaara.com/wp-content/uploads/2011/01/DCD1-pic4-small-300x162.png" alt="" width="300" height="162" /></a></p>
<p>You are now able to call information from the database, edit it, and when you click &#8220;Submit&#8221; you will see the change reflected in the DataGrid. It is important to understand that code which is generated by FB4 does not commit any change to the database itself, so once you refresh the page your changes are lost. Don&#8217;t worry about this now, we will fix this shortly.</p>
<p><strong>Delete Person from Database by id</strong><br />
Step 1. From the Data/Services tab, click and highlight <code>deletePerson(itemID:int):void</code> and click on the &#8220;Generate Form&#8221; button.</p>
<p>Step 2. Uncheck the checkbox labeled &#8220;Form for return box&#8221; in the section labeled &#8220;Create&#8221;</p>
<p>Step 3. Click the &#8220;Finish&#8221; button</p>
<p>Step 3. Save and run the application</p>
<p>You are now able to choose an id from the list and delete it based on the Person id. Again, make note that the changes are not being committed to the database.</p>
<p><strong>Create Person in Database</strong><br />
Follow the same steps above, but this time using <code>createPerson(item:Person):int</code> from the Data/Services tab to generate the form. What you will notice this time, is that when you run the application, the create functionality does not seem to work at all. This is nothing to be concerned about though, you have done nothing wrong. We just need to make a few tweaks in the code to get all of the functionality working as you would expect.</p>
<p><strong>Moving into Source View</strong><br />
Now that we are in source view we can add the additional lines of code needed to make this application function as it should.</p>
<p>Lets first start by working on the create functionality. There are two reasons why when we currently click the &#8220;Create&#8221; button that we are not seeing anything happen.</p>
<p>1.	FB4 is not committing the new record to the database<br />
2.	Even if it was, the DataGrid is not updating after the button click so we would not be able to see the change anyway</p>
<p>To make this work we need to make a few modifications to the function being called when the user clicks the create button.</p>
<p>Change From:</p>
<pre>protected function button4_clickHandler(event:MouseEvent):void
  {
    var person3:Person = new Person();
    person3.id = parseInt(idTextInput2.text);
    person3.name = nameTextInput2.text;

    createPersonResult.token = personService.createPerson(person3);
  }</pre>
<p>Change To</p>
<pre>protected function button4_clickHandler(event:MouseEvent):void
  {
    var person3:Person = new Person();
    person3.id = parseInt(idTextInput2.text);
    person3.name = nameTextInput2.text;

    createPersonResult.token = personService.createPerson(person3);
    createPersonResult.token = personService.commit();
    getAllPersonResult.token = personService.getAllPerson();
  }</pre>
<p><code>createPersonResult.token = personService.commit();</code> tells the database to commit the new record, while <code>getAllPersonResult.token = personService.getAllPerson();</code> tells the dataGrid to get its data again. Now, save and run the application to see that the new functionality is working.</p>
<p>Lets go ahead and make the needed changes to the delete and edit functions to also get them committing to the database.</p>
<p><strong>Committing the Delete Function to the Database</strong><br />
To get the delete button to commit its changes to the database we need to add the following line of code <code>deletePersonResult.token = personService.commit();</code></p>
<p>Change From:</p>
<pre>protected function button3_clickHandler(event:MouseEvent):void
  {
    deletePersonResult.token = personService.deletePerson(parseInt(itemIDTextInput2.text));
  }</pre>
<p>Change To:</p>
<pre>protected function button3_clickHandler(event:MouseEvent):void
  {
    deletePersonResult.token = personService.deletePerson(parseInt(itemIDTextInput2.text));
    deletePersonResult.token = personService.commit();
  }</pre>
<p><strong>Committing Edits to the Database</strong><br />
This isn’t quite as simple as the delete because we have to manually add <code>updatePerson(item:Person):void</code>. This is a two step process.</p>
<p>Step 1. Add the following line of code updatePersonResult.token = personService.commit(); to the function called when the user clicks submit. This will tell the function to also commit the change to the database.</p>
<pre>protected function button2_clickHandler(event:MouseEvent):void
  {
    person.id = parseInt(idTextInput.text);
    person.name = nameTextInput.text;
    updatePersonResult.token = personService.commit();
  }</pre>
<p>Step 2. Add <code>&lt;s:CallResponder id="updatePersonResult"/&gt;</code> to Declarations or we will end up with the following error: &#8220;1120: Access of undefined property updatePersonResult.&#8221;</p>
<p>If we run our flex application now, we notice that although functional, it is not very pretty or user friendly. In Part 2 of this entry, you will remove all of the unneeded components in order to make the application easy to use, and something more like what you would see in a real world application.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.anaara.com/archives/295/feed</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Adventures in Printing with Flex 4</title>
		<link>http://blog.anaara.com/archives/303</link>
		<comments>http://blog.anaara.com/archives/303#comments</comments>
		<pubDate>Thu, 03 Feb 2011 21:17:53 +0000</pubDate>
		<dc:creator>Dan Orlando</dc:creator>
				<category><![CDATA[Adobe]]></category>
		<category><![CDATA[Flash]]></category>
		<category><![CDATA[Flex]]></category>
		<category><![CDATA[Flex 4]]></category>
		<category><![CDATA[Print]]></category>
		<category><![CDATA[RIA]]></category>
		<category><![CDATA[flash]]></category>
		<category><![CDATA[print]]></category>

		<guid isPermaLink="false">http://blog.anaara.com/?p=303</guid>
		<description><![CDATA[I was recently tasked with a Flex print requirement that turned out to be far more complex than I could have anticipated. I knew that Flex wasn&#8217;t particularly good when it came to printing (which is probably an understatement), but &#8230; <a href="http://blog.anaara.com/archives/303">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>I was recently tasked with a Flex print requirement that turned out to be far more complex than I could have anticipated. I knew that Flex wasn&#8217;t particularly good when it came to printing (which is probably an understatement), but I really thought it had advanced since the last time I made an attempt at print with Flex a couple years ago. Based on the little bit of research that I did, it appears that everyone is pretty much just as in the dark as I am in terms of the reasoning behind Adobe&#8217;s decision that print wasn&#8217;t necessary or wasn&#8217;t important enough to put a considerable amount of time and energy toward it.</p>
<p>Flex is incredibly good at a lot of things, particularly data dashboards. I&#8217;ve had a number of business executives that have been stuck with Excel for years start drooling right in front of me after showing them some of the dashboards I&#8217;ve worked on. As Flex continues to evolve as a UI development tool for complex data dashboards, and as our clients continue to see it&#8217;s powerful capabilities, the logical progression is that Flex developers are now receiving requirements that involve reporting capabilities… and reporting capabilities means &#8211; you guessed it &#8211; PRINTING (gasps). The fact of the matter is, the line between data dashboards and reporting has become blurry at best.</p>
<p>Let&#8217;s take a moment to put this into perspective. There are so many areas of a business where employees of a company must be able to make sense of large amounts of data and form logical conclusions based on how that data is presented so that they can make important decisions.  Furthermore, as I stated earlier, Flex is particularly good at providing developers with the tools that are necessary to fulfill these needs. When you provide business professionals with a means of making decisions based on conclusive evidence in the form of data representation, it only makes sense that they must be able to print that data representation to show to their constituencies to support their argument for the decision that they made, which was based on the reports they generated.</p>
<p>Ok, so I&#8217;ve established the importance of being able to print from Flex, so let&#8217;s look at the current options for a business professional who is about to make a presentation to an important executive at his company. First, there is the ghetto way to do it: he could do a simple screenshot of the Flex data dashboard using shift-cmd-4 on Mac or Shift-&#8221;Print Screen&#8221; (I think that&#8217;s what it is) on PC and try to import the resulting image into his presentation tool. The problem here is that the result isn&#8217;t going to look very good when it&#8217;s printed because of the low resolution.</p>
<p>Developers have the option of implementing a third-party library to try and solve their print requirements. I did a lot of research on this, and found that AlivePDF is currently the best bet. However, there is still much work to be done; far more than Thibault Imbert could, the creator of AlivePDF, could handle alone. The library has been in development for four years and it&#8217;s capabilities are impressive in comparison to the pathetic print capabilities that are built into the Flex framework. It handles the printing of charting components wonderfully. However, it&#8217;s ability to handle the printing of lengthy datagrids is pretty terrible. Now, I don&#8217;t want to discredit the work of Thibault Imbert in any way. If it weren&#8217;t for him, I would have never made it as far as I have on my current requirement in such a short period of time. So believe me when I say that I have a lot of respect for Thibault (apparently Adobe felt the same way, because they made him Product Manager for the Flash Player, which is pretty cool!).</p>
<p>I have to also consider the fact that support for grid-printing has only really been implemented in the last year based on the release notes. The problem is that it is easy to think that grid printing would be pretty simple, but there are a lot of factors that play a role. For example, wrapping text in a cell increases the height of that row, resulting in part of the bottom row being sliced off on that page. Then, when attempting to truncate the text as a solution, the text for all of the rows became misaligned, with text from one row falling on top of the text of another. So my next endeavor is to figure that one out.</p>
<p>The bottom line here is that print really needs to get the attention it deserves now so we have it for the next major release of Flex, and I will certainly be voicing this concern to our friends at Adobe as a result of a particularly painful couple of months working on this.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.anaara.com/archives/303/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Deep Linking with Flex 4 using Fragments</title>
		<link>http://blog.anaara.com/archives/287</link>
		<comments>http://blog.anaara.com/archives/287#comments</comments>
		<pubDate>Wed, 26 Jan 2011 01:46:23 +0000</pubDate>
		<dc:creator>Dan Orlando</dc:creator>
				<category><![CDATA[ActionScript]]></category>
		<category><![CDATA[Flex 4]]></category>
		<category><![CDATA[RIA]]></category>

		<guid isPermaLink="false">http://blog.anaara.com/?p=287</guid>
		<description><![CDATA[The objective of deep linking is typically centered on creating functions that either serialize the current state to the URL or deserialize the URL and use that information to change the state of the application. This makes it possible to bookmark a specific state of your Flex application.... <a href="http://blog.anaara.com/archives/287">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<div>The objective of deep linking is typically centered on creating functions that either serialize the current state to the URL or deserialize the URL and use that information to change the state of the application. This makes it possible to bookmark a specific state of your Flex application. The main ingredient for this deep linking implementation is called a &#8220;fragment&#8221;. You&#8217;ve probably seen these used before in HTML or Javascript. A fragment is separated from the URL using the hash mark symbol (#). For example, fragments are used when anchoring items of an HTML web page. A &#8220;frequently asked questions&#8221; page is the first thing that comes to mind for me because there are so many FAQ pages on the web that list the questions at the top of the page and when you click on a question, the scrollbar jumps down to the respective answer for the question you clicked on. However, in Flex, you can use this same concept to tell your application what state it should be in or even the state of a specific component!</div>
<div>Note that when using URL fragments for deep linking, you actually want to keep the built-in history management off, otherwise it will interfere with fragment processing.</div>
<p></p>
<div><strong>Step 1</strong></div>
<div>Start by declaring three variables:</div>
<div>1) a reference to the Flex BrowserManager class,</div>
<div>2) a flag to signal that URL parsing is in progress, and</div>
<div>3) a variable to hold the title for the browser&#8217;s title bar.</div>
<pre>public var browserManager:IBrowserManager;
private var isParsing:Boolean;
private var title:String;</pre>
<div><strong>Step 2</strong></div>
<div>Now, you need to declare your states of your application if you haven&#8217;t already and place a listener for the enterState event. When the state changes, a call to updateURL will be made.</div>
<p></p>
<pre>
&lt;s:states&gt;
    &lt;s:State name="Home" enterState="updateURL()" /&gt;
   &lt;s:State name="About" enterState="updateURL()" /&gt;
   &lt;s:State name="Services" enterState="updateURL()" /&gt;
   &lt;s:State name="Store" enterState="updateURL()" /&gt;
&lt;/s:states&gt;
</pre>
<div><strong>Step 3</strong></div>
<div>When the application loads, you&#8217;ll need to initialize the BrowserManager, and register two listeners, one for when the browser&#8217;s URL changes and the other for when the application&#8217;s state changes. Lastly, you&#8217;ll use the callLater() method of UIComponent to parse the URL. Note that this function is called on creationComplete of the Application tag.</div>
<p></p>
<pre>
private function application_creationCompleteHandler():void
{
   browserManager = BrowserManager.getInstance();
   browserManager.init("", "Home");
   browserManager.addEventListener(BrowserChangeEvent.BROWSER_URL_CHANGE, parseURL);
   callLater(parseURL);
}
</pre>
<div><strong>Step 4</strong></div>
<div>Now write the code for your parseURL() function. This function will be called whenever the BROWSER_URL_CHANGE event fires. The function parses the URL, and if fragments are found, it will change the title and state of the application accordingly.</div>
<p></p>
<pre>
private function parseURL(event:Event = null):void
{
   isParsing = true;
   var o:Object = URLUtil.stringToObject(browserManager.fragment);
   if (o.view == undefined)
      o.view = "Home";
   currentState = o.view;
   title = currentState;
   browserManager.setTitle(title);
   isParsing = false;
}
</pre>
<div><strong>Step 5</strong></div>
<div>You are now successfully updating the application from the URL! The next thing you need to do is update the URL from the application though. We&#8217;ll accomplish this with the function updateURL().</div>
<p></p>
<pre>
private function updateURL():void
{
   title = currentState;
   var fragments:String = "";
   var o:Object = {};
   if (currentState != "Home")
      o.view = currentState;

   fragments = URLUtil.objectToString(o);
   browserManager.setTitle(title);
   browserManager.setFragment(fragments);
}
</pre>
<div></div>
<div>And that&#8217;s all there is to it. Happy Flexing!</div>
<div>-Dan Orlando</div>
]]></content:encoded>
			<wfw:commentRss>http://blog.anaara.com/archives/287/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

