August 1, 2014
Hot Topics:
RSS RSS feed Download our iPhone app

Forms Validation with Symfony and Prototype

  • December 11, 2006
  • By Jason Gilmore
  • Send Email »
  • More Articles »

The last two installments of this ongoing PHP series focused on the advantages of frameworks, demonstrating just how much time and effort they can eliminate doing otherwise tedious tasks such as building backend management scaffolds and performing forms validation. These tutorials focused on the increasingly popular CakePHP framework, however in this installment I'll switch gears a bit and instead examine my preferred framework solution: symfony. Specifically, I'll show you how symfony's built-in support for the Prototype JavaScript framework can greatly enhance the user experience within your applications.

I'll presume you're already familiar with symfony, however you'll still gain a lot from this article if you've experience with another framework solution such as Rails or CakePHP. The symfony website offers several great tutorials and screencasts, so if this topic is entirely new to you head on over there before proceeding.

Introducing Prototype

Most would agree writing JavaScript just isn't fun. But as the web becomes increasingly central to both personal and corporate livelihoods, user expectations for web applications that more closely resemble their desktop brethren continues to grow. The most notable solution for creating these sorts of applications is Ajax, which is really just a fancy name for JavaScript. Therefore if you're going to create truly compelling web applications, it's time to master the language you've grown to hate. Thankfully, you're not alone, and true to form, programmers recently began to seek out ways to minimize the programmatic pain experienced when using JavaScript. One of the most popular solutions devised so far is Prototype, a JavaScript library which abstracts much of JavaScript's esoteric syntax. For example, JavaScript makes it easy to access any node in the DOM by constructing a referential string. Consider the following HTML form:

<form method="post" name="productform" id="productform"
      action="/buy" onsubmit="return validate()">
   <label id="bclabel" for="bookcopies">
      How many copies would you like to purchase:
   </label><br />
   <input type="text" name="bookcopies" id="bookcopies" value="0"
          size="2" maxlength="2" /><br />
   <input type="submit" name="commit" value="Update Cart" />
</form>

This produces a form which looks like the below screenshot:

Suppose you wanted to validate the bookcopies field, perhaps prompting the user if he enters a value greater than 10:

function validate() {
   if (document.productform.bookcopies.value > 10) {
      alert("You can purchase a maximum of 10 copies.");
      return false;
   }
   return true;
}

But because referencing form elements within JavaScript is so commonplace, Prototype provides you with an easy shortcut:

function validate() {
   if ($F('bookcopies') > 10) {
      alert("You can purchase a maximum of 10 copies.");
      return false;
   }
   return true;
}

But this is just a taste of what Prototype brings to the table. Let's build on this example, using Prototype's Ajax capabilities to prompt the user to complete the bookcopies field if it's empty upon form submission. The following function will insert a reminder directly following the bookcopies field label, informing the user that the field must be completed before the form can be submitted:

function validate() {
   if ($F('bookcopies') == 0) {
      new Insertion.After('bclabel', ' <b>(Required!)</b>');
      return false;
   }
   return true;
}

Should the user enter 0 or leave the form blank, upon submitting the form an error message will appear as depicted in this screenshot:

As you can see, writing JavaScript is a breeze with Prototype! But as the next section will demonstrate, when combined with the power of the symfony framework, you'll be able to create and validate forms in a manner that's more methodical, programmatically sound, and enjoyable than ever before.

Integrating Prototype with symfony

symfony is packaged with the latest version of Prototype; all you need to do is enable it within the desired application action. This is done using the addJavaScript() method, like so:

$this->getResponse()->addJavascript('/sf/js/prototype/prototype');

Alternatively, you can make the library available to your entire application by adding the following line to your view.yml configuration file:

javascripts: [/sf/js/prototype/prototype]

Once done, you're free to begin taking advantage of Prototype's syntax. To begin, let's recreate the earlier HTML form. You have the option of either using standard HTML syntax, or symfony's forms helper syntax. Because I'm a programmer, and for current projects am responsible for both the website design and logic, I prefer the latter and so will use it here:

<p>
   <?php echo form_tag('buy', Array('name' => 'productform', 'id' => 'productform', 
                       'onsubmit' => 'return validate()')) ?>
      <label id="bclabel" for="bookcopies">How many copies would you like to purchase: </label> <br />
      <?php echo input_tag('bookcopies', '', array('size' => 2, 'maxlength' => 2)) ?><br />
      <?php echo submit_tag('Update Cart') ?><br />
   </form>
</p>

You have the option of storing the JavaScript within a number of locations, including the symfony template, or preferably within symfony's predefined js/ directory. If you choose the latter, be sure to include it within the template like so:

<script src="/js/developer/validation.js" type="text/javascript"></script>

In either case, the JavaScript looks exactly as before:

function validate() {
   if ($F('bookcopies') == 0) {
      new Insertion.After('bclabel', ' <b>(Required!)</b>');
      return false;
   }
   return true;
}

Hopefully this tutorial left your mind racing regarding the possibilities symfony and Prototype provide for making you a more productive, efficient developer. If you build anything particularly interesting based on what you've learned, please let me know about it by emailing wjATwjgilmore.com! The next article builds on what you've learned here, showing you how to use symfony's JavaScript helpers to integrate more advanced Ajax features into your applications.

About the Author

W. Jason Gilmore (http://www.wjgilmore.com/) is the open source editor for Apress. He's the author of the best-selling "Beginning PHP and MySQL 5: Novice to Professional, Second Edition" (Apress, 2006. 913pp.). Along with Robert Treat, Jason is the co-author of "Beginning PHP 5 and PostgreSQL 8: From Novice to Professional". Jason loves receiving e-mail; so don't hesitate to write him at wjATwjgilmore.com.






Comment and Contribute

 


(Maximum characters: 1200). You have characters left.

 

 


Sitemap | Contact Us

Rocket Fuel