Receive user submitted data with Zend

zend-logoEvery PHP developer has to write them and these are essentialy an interface for a user to enter data. Nothing too scary, it’s something we all do online from filling out online banking details to filling in your name and address for something that you’ve bought online.

Adigi can make it incredbily easy to collection information from users. That’s because we’ve excellent designers who can provide useable web pages for a whole range of browsers. Data can be collected and stored in files, database and even documents such as spreadsheets. This functionality is provided by a PHP developer such as myself. I want to share with you something I’ll always consider, should a project meet the following criteria:

  • New or existing website in PHP with no clear structure, framework or consistency.
  • Guaranteed availablity of the Zend Framework.
  • Good support for validation required.

Using an example of a contact form, we’ll imagine that there’s two PHP pages, one to send the data and one to catch and validate the received $_POST data. This is not an ideal arrangement because an entire chunch of validation logic will need to be shoved inbetween. And there’s even more work trying to get the right key / value pairs out to persist the information once the page has loaded again. Then there’s the thank you message. How will you know if there’s been a problem along the way? Before you know it, you’ve lovely HTML and CSS has been polluted with sloppy PHP statements that could behave badly.

One solution is: the Zend_Form class! Which is a class you will write to sit between the two files of your contact form project. If you are lucky and your project has the Zend library all ready bootstrapped (available) you can start using it write away. Otherwise, read this.

Create yourself a new file with a class definition to extend from the standard Zend_Form class. Save it somewhere within you’re project, ideally in a bootstrapped class library such as “lib/forms”.

<?php
class Lib_Form_Contact extends Zend_Form
{
  // Load a form with default values
  public function init()
  {
      // Input for first name
      $input = $this->createElement('text','first_name')
      $this->addElement($input);

      // Input for email address
      $input = $this->createElement('text','email_address')
                  ->addValidator('EmailAddress');
      $this->addElement($input);

      $input = $this->createElement('select','salutation')
                  ->addMultiOption('', '-- None --')
                  ->addMultiOption('mr', 'Mr')
                  ->addMultiOption('mrs', 'Mrs')
                  ->addMultiOption('miss', 'Miss');
      $this->addElement($input);
  }

  // Add your own validation rules
  public function isValid($data)
  {
      $someOtherObject = new someOtherClass;
      if ( ! $someOtherObject->isOk($data))
      {
          $this->getElement('email_address')
                  ->setErrorMessages(
                          array(
                                  Zend_Validate_Alpha::INVALID => "Error Message",
                          )
                      );
      }

      // Don't forget to include Zend_Form (parent class)
      // it will want to complete the rest of it's own validation
      return parent::isValid($data);
  }

  // Have your own methods
  public function saveInDatabase()
  {
      $data = $this->getValues();
      $this->yourDatabaseHandler->save($data);
  }
}
?>

It’s worth to note. There’s a range of elements that you can use such as select options, hidden inputs and textarea elements that are supported by Zend_Form and can be used at this point within your class.

Your new class is ready to use within your contact form HTML as follows:

<?php
// Make objects - start afresh 
$form = new Lib_Form_Contact();
$view = new Zend_View; 
$isSucess = false; 

// Check for button click 
if ($form->isValid($_POST)):
    $isSucess = true;
    // Save provided information in database, perhaps by method within the form class
    $form->addToDatabase();
    // Send email to the client regarding the contact
    $form->notifyListener();
    echo "Thanks for your enquiry";
else:
    // Show the form errors
    print_r($this->getErrors());
endif;

// Shove any data in the $_POST into your form
$form->populate($_POST);
// present your form to the world with a view object.
echo $form->render($view);

// Alternatively - list each element in turn.
echo $form->email_address->render($view);
?>

The PHP and HTML code above will list the form for you. It will load your posted values in the form on post back. Or load them directly from another source via the populate() method. It will also give a basic response once the user has submitted the form.

The main benefits of this approach is:

  • Flexibility, new or existing form elements can be added or removed without risk.
  • Extra validation can be applied or removed at any point.
  • All major pieces of PHP or functionality are kept away from any HTML that a designer may work on.
  • A majority of the validation is taken care of by Zend_Form.
  • Access for data with confidence by running $form->email_address->getValue()
  • Eliminate the nasty undefined index error message when using the $_POST collection directly.

Hope you enjoyed reading this as much as I did writing it. I’ll expand should there be any interest.

Get in Touch.