Tutorial Q&A PDF

1st September 2009

Chris Kirk has kindly provided a Q&A PDF which summarises a number of problems that have been raised and answered in the comments on the tutorial page. If you are having problems, download it and see if it helps.

Thanks Chris!

Simple Zend_Form Example

21st February 2008

Following on from the Simple Zend_Layout Example, Zend_Form is now in the trunk, so here's a super simple, complete example that shows it in action:

Zend_Form screenshot1.png

(clearly the form is unstyled :)

You can construct a Zend_Form directly from a config file or can build it in code. This example builds it in code.

Setting up

This example uses the same basic skeleton as the Zend_Layout code with the addition of a forms directory:

Zend_Form Directory Layout.png

As you can see, I've added a forms directory within the application subdirectory with our form file, ContactForm.php, in it.

The contact form

To keep the form contained, I've put it in its own class which extends from Zend_Form. The file is application/forms/ContactForm.php and so the class is forms_ContactForm so that Zend_Loader can easily load it:


class forms_ContactForm extends Zend_Form 
{ 
    public function __construct($options null) 
    { 
        parent::__construct($options);
        $this->setName('contact_us');
        
        $title = new Zend_Form_Element_Select('title');
        $title->setLabel('Title')
              ->setMultiOptions(array('mr'=>'Mr''mrs'=>'Mrs'))
              ->setRequired(true)->addValidator('NotEmpty'true);
        
        $firstName = new Zend_Form_Element_Text('firstName');
        $firstName->setLabel('First name')
                  ->setRequired(true)
                  ->addValidator('NotEmpty');

        $lastName = new Zend_Form_Element_Text('lastName');
        $lastName->setLabel('Last name')
                 ->setRequired(true)
                 ->addValidator('NotEmpty');
             
        $email = new Zend_Form_Element_Text('email');
        $email->setLabel('Email address')
              ->addFilter('StringToLower')
              ->setRequired(true)
              ->addValidator('NotEmpty'true)
              ->addValidator('EmailAddress'); 
              
        
        $submit = new Zend_Form_Element_Submit('submit');
        $submit->setLabel('Contact us');
        
        $this->addElements(array($title$firstName, 
            $lastName$email$submit));
        
    } 
}

We set the name of the form first and then create five elements; one select box for the title, three text boxes for first name, surname and email address and then finally a submit button. Note that as we have overridden the constructer, we also call up to the parent's constructor so that all the Zend_Form initialisation happens.

Creating an element is quite simple. Each element is of the type Zend_Form_Element_Xxx where Xxx is the type, such as Text, Submit, Select, etc. We then configure the element how we want it, such as setting a label and adding filters and validators. Finally we add all the elements to the form using the addElements() function.

Note that if you have multiple validators, you can pass in true as the second parameter ($breakChainOnFailure) to stop processing the remaining validators at that point. This can be because the further validators do not make sense or because you only ever want the user to see one message per field to avoid overwhelming them.

Displaying the form

Having defined out form, we need to get it to the screen. In the controller we need the following:


class IndexController extends Zend_Controller_Action
{
    function indexAction()
    {
        $this->view->pageTitle "Zend_Form Example";
        $this->view->bodyCopy "<p >Please fill out this form.</p>";

        $form = new forms_ContactForm();
        $this->view->form $form;
    }
}

This code assigns some variables to the view, then instantiates the form and assigns that to the view also. The view script is similarly simple:

view/scripts/index/index.phtml:

<?php echo $this->pageTitle ;?>
<?php echo $this->bodyCopy ;?>

<?php echo $this->form ;?>

To render the form, we simply echo it. By default, the form is marked up as a definition list and its HTML looks like this:


<form name="contact_us" id="contact_us" enctype="application/x-www-form-urlencoded" action="" method="post"><dl class="zend_form">
<dt><label for="title" class="required">Title</label></dt>
<dd>
<select name="title" id="title">
    <option value="mr" label="Mr">Mr</option>
    <option value="mrs" label="Mrs">Mrs</option>
</select></dd>
<dt><label for="firstName" class="required">First name</label></dt>
<dd>
<input type="text" name="firstName" id="firstName" value=""></dd>
<dt><label for="lastName" class="required">Last name</label></dt>
<dd>
<input type="text" name="lastName" id="lastName" value=""></dd>
<dt><label for="email" class="optional">Email address</label></dt>
<dd>
<input type="text" name="email" id="email" value=""></dd>
<dt></dt><dd>
<input type="submit" name="submit" id="submit" value="Contact us"></dd></dl></form>

Notice how the setRequired() has resulted in the "required" CSS class name being applied to those elements.

Decorators

If you do not want to use a definition list, then this can easily be changed using decorators. For instance, adding the following to the bottom of the form's constructor after the addElements() call:


        $this->clearDecorators();
        $this->addDecorator('FormElements')
         ->addDecorator('HtmlTag', array('tag' => '<ul>'))
         ->addDecorator('Form');
        
        $this->setElementDecorators(array(
            array('ViewHelper'),
            array('Errors'),
            array('Description'),
            array('Label', array('separator'=>' ')),
            array('HtmlTag', array('tag' => 'li''class'=>'element-group')),
        ));

        // buttons do not need labels
        $submit->setDecorators(array(
            array('ViewHelper'),
            array('Description'),
            array('HtmlTag', array('tag' => 'li''class'=>'submit-group')),
        ));

will result in the form being marked up as an unsigned list with each label and element pair inside each <li>. The marked up form looks like this:


<form name="contact_us" id="contact_us" enctype="application/x-www-form-urlencoded" action="" method="post"><ul>
<li class="element-group"><label for="title" tag="" class="required">Title</label> 
<select name="title" id="title">
    <option value="mr" label="Mr" selected="selected">Mr</option>
    <option value="mrs" label="Mrs">Mrs</option>
</select></li>
<li class="element-group"><label for="firstName" tag="" class="required">First name</label> 
<input type="text" name="firstName" id="firstName" value=""></li>
<li class="element-group"><label for="lastName" tag="" class="required">Last name</label> 
<input type="text" name="lastName" id="lastName" value=""></li>
<li class="element-group"><label for="email" tag="" class="required">Email address</label> 
<input type="text" name="email" id="email" value=""></li>
<li class="submti-group"><input type="submit" name="submit" id="submit" value="Contact us"></li></ul></form>

As you can see, the decorator system makes it easy to render our form in the manner we wish. As a note of warning, pay attention to the order of the decorators as it matters!

Processing

The form is now displayed, so when the user presses the button we need to process it. In this example, this is done in the indexAction() controller function, so that the complete function looks like this with the addition in bold:


class IndexController extends Zend_Controller_Action
{
    function indexAction()
    {
        $this->view->pageTitle "Zend_Form Example";
        $this->view->bodyCopy "<p>Please fill out this form.</p>";

        $form = new forms_ContactForm();

        if ($this->_request->isPost()) {
            $formData $this->_request->getPost();
            if ($form->isValid($formData)) {
                echo 'success';
                exit;
            } else {
                $form->populate($formData);
            }
        }

        $this->view->form $form;
    }
}

Firstly we check the the request is a POST using the request object's isPost() function and then we use validate the submitted data using the form's isValid() function. If this returns true, then we have valid data and can process. If the data is not valid, we populate the form's elements with it and then redisplay so that the user can correct appropriately. The default decorators will display an error message next to each element that failed validation.

Conclusion

So there you have it. A very simple example of how to use Zend_Form.

Here's a zip file of this project: Zend_Form_Example.zip (It includes a snapshot of the trunk of the Zend Framework which is why it's 3MB big.)

It works for me, at least.

Update

With the release of Zend Framework 1.5, a change was made to the way buttons work and you should not put a label decorator on a button as the label property of a button is used for the text value of the button itself.

I have updated the code above to show that if you use setElementDecorators() you then need to reset the decorators for any buttons, the $submit button, in this case. I have also put back the Errors decorator when using an unsigned list.

Simple Zend_Layout Example

11th December 2007

Zend_Layout is in the trunk now, so here's a super simple MVC example that shows it in action:
Zend_Layout Example_Small.png

This example consists of three view files: the outer layout file, the index action view script and a right hand side bar. The remainder of this post describes the key files. If you just want to poke around with the code, then it's at the bottom, so page down now!

Setting up

This is the directory layout:

Zend_Layout Directory.png

As you can see, it's the standard layout and we have one controller, Index, with one action (also index). For good measure, I've thrown in a view helper to collect the base URL to reference the CSS file and also render into a sidebar.

Let's look at the bootstrap file, index.php, first:

<?php

define('ROOT_DIR'dirname(dirname(__FILE__)));

// Setup path to the Zend Framework files
set_include_path('.'
PATH_SEPARATOR ROOT_DIR.'/lib/'
PATH_SEPARATOR get_include_path()
);

// Register the autoloader
require_once 'Zend/Loader.php';
Zend_Loader::registerAutoload();

// Initialise Zend_Layout's MVC helpers
Zend_Layout::startMvc(array('layoutPath' => ROOT_DIR.'/app/views/layouts'));

// Run!
$frontController Zend_Controller_Front::getInstance();
$frontController->addControllerDirectory(ROOT_DIR.'/app/controllers');
$frontController->throwExceptions(true);
try {
    $frontController->dispatch();
} catch(Exception $e) {
    echo nl2br($e->__toString());
}


This is a standard bootstrap with the exception that we initialise the Zend_Layout using the startMvc() function. This takes an array of options, but the one thing you really need to pass in is the directory to find the layout files. I've chosen app/views/layouts as it makes sense in this case. If you are using modules, then maybe app/layouts would be better.

The controller

The index controller contains two functions: init() to render the sidebar to a named response section for use in the layout and then the indexAction() which just puts some text into the view:

<?php

class IndexController extends Zend_Controller_Action
{
    function init()
    {
        // Render sidebar for every action
        $response $this->getResponse();
        $response->insert('sidebar'$this->view->render('sidebar.phtml')); 
    }

    function indexAction()
    {
        $this->view->pageTitle "Zend Layout Example";

        $this->view->bodyTitle '<h1>Hello World!</h1>';
        $this->view->bodyCopy "<p>Lorem ipsum dolor etc.</p>";
    }
}

Two-step view

The view is now two-step. This means that we split our HTML between multiple files. The first step is to render the "inner" scripts, such as the sidebar and the action specific scripts. Then we render the "outer", layout script which embeds the rendered "inner" scripts.

The "inner" scripts

The action view script, index/index.phtml is trivial as it just needs to display the text relevant to the index action only:

<?php echo $this->bodyTitle ;?>
<?php echo $this->bodyCopy ;?>

(told you it was simple!)

The sidebar.phtml is similarly, just the HTML required for our sidebar:


<h2>Sidebar</h2>
<ul>
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
<li>Item 4</li>
<li>Item 5</li>
</ul>

Again, nice and easy HTML, for this example at least!

The layout script

The layout script, layout.phtml, ties it all together. It contains the HTML that is common to all pages on our website and uses the special construct <?php echo $this->layout()->content ?> to render a named response segment. Note that the view renderer will render to "content" for the action controller's script.

The layout script looks like this:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title><?php echo $this->escape($this->pageTitle); ?></title>
    <link rel="stylesheet" href="<?php echo $this->baseUrl(); ?>/main.css" type="text/css">
</head>
<body>
    <div id="content">
        <?php echo $this->layout()->content ?>
    </div>
    <div id="sidebar">
        <?php echo $this->layout()->sidebar?>
    </div>
</body>
</html>

For simplicity, we use the baseUrl view helper to retrieve the base URL from the request (via the Front Controller) and we render our two named response segments (content and sidebar) using the view helper layout() which is provide by Zend_Layout.

Conclusion

That's all there is to it. We could have use the partial() view helper to render the sidebar script and coming soon to a svn tree near you is other useful view helpers such as headScript() and headTitle() which will make the <head> section easier to manage.

Here's a zip file of this project: Zend_Layout_Example.zip(It includes a snapshot of the trunk of the Zend Framework which is why it's 3MB big.)

It works for me, at least.

Notes on using Oracle with my tutorial

6th June 2007

William Graham has been playing with the Zend Framework and Oracle using my tutorial.

His notes are very useful if you want to get my admittedly MySQL-centric tutorial working with Oracle. I've come across that uppercase field name thing before in an application I wrote at work that needed to transfer some data from Oracle to SQL Server. Took me a while to work out what was going on.

I'm a little confused about the case of form element names in $_POST, so will have to test that at some point.