In this second part of the HTML_QuickForm primer, I will demonstrate the advanced features of the package - these include "hierarchical" drop downs, "auto-complete" text boxes, integration with the "Smarty" template engine, and much, much more.
Using HTML_QuickForm To Manage Web Forms, Part 2 - End Game (Page 6 of 7 )
One last example before I bring the curtains down on this two-part tutorial. So far, I have covered all aspects of the Web form except one critical feature. Pat yourselves on the back if your answer was "file uploads using a Web form."
Load this example in the browser to view the following:
This Web file allows you to upload an MPEG Layer 3 (a.k.a. MP3) file to the server. I gave it a simple test run and got the following output:
Note that the Web form has been configured to reject files that are not MP3 files. When I attempted to upload a file with a different extension, the Web form threw the following error message:
As seen from the output above, this PHP script is intelligent. But what is source of this intelligence? Read on.
// define a new HTML_QuickForm object $obj_songfileupload_form = new HTML_QuickForm('frmSongFileUpload', true);
It all begins with the instantiation of a HTML_QuickForm object - note that the second parameter has been set to "true" in order to indicate that I will use this Web form for file uploads.
// add 'upload' control and associated rules $obj_songfileupload_form->addElement('file', 'ctlFileUpload', 'Select Song:');
$obj_songfileupload_form->addRule('ctlFileUpload', 'Please select a Song file to upload.', 'uploadedfile'); $obj_songfileupload_form->addRule('ctlFileUpload', 'The extension of the Song file should be *.mp3', 'filename', '/^.*\.mp3$/'); $obj_songfileupload_form->addRule('ctlFileUpload', 'The MIME type of the uploaded Song file is not valid.', 'mimetype', 'audio/mpeg');
Next, I have passed the "file" keyword to the addElement() method to include a file upload <FORM> control in the Web form. Then, I have added some "file" control-specific rules:
The 'uploadedfile' rule is synonymous to the 'required' rule for text controls; it ensures that a file is selected for upload.
The 'filename' rule allows me to specify a pattern for the name of the file using a regular expression; in my example, the regex ensures that the uploaded file has a ".mp3" extension.
The 'mimetype' rule enforces MIME-type restrictions on the uploaded file; if it does not match the required file type, an error is thrown. You may want to add more MIME-types based on your requirement.
Once the upload file has been validated, I store it on the server by invoking the store_song_file() function via the process() method, as seen above. This callback function, in turn, uses copy()to store the file at the required destination.