Programmer's Reference Guide

Create a Model and Database Table

Create A Form

For our guestbook to be useful, we need a form for submitting new entries.

Our first order of business is to create the actual form class. To create the empty form class, execute:

  1. % zf create form Guestbook
  2. Creating a form at application/forms/Guestbook.php
  3. Updating project profile '.zfproject.xml'

This will create the directory application/forms/ with the classfile Guestbook.php. Open that file and update it so it reads as follows:

  1. // application/forms/Guestbook.php
  2.  
  3. class Application_Form_Guestbook extends Zend_Form
  4. {
  5.     public function init()
  6.     {
  7.         // Set the method for the display form to POST
  8.         $this->setMethod('post');
  9.  
  10.         // Add an email element
  11.         $this->addElement('text', 'email', array(
  12.             'label'      => 'Your email address:',
  13.             'required'   => true,
  14.             'filters'    => array('StringTrim'),
  15.             'validators' => array(
  16.                 'EmailAddress',
  17.             )
  18.         ));
  19.  
  20.         // Add the comment element
  21.         $this->addElement('textarea', 'comment', array(
  22.             'label'      => 'Please Comment:',
  23.             'required'   => true,
  24.             'validators' => array(
  25.                 array('validator' => 'StringLength', 'options' => array(0, 20))
  26.                 )
  27.         ));
  28.  
  29.         // Add a captcha
  30.         $this->addElement('captcha', 'captcha', array(
  31.             'label'      => 'Please enter the 5 letters displayed below:',
  32.             'required'   => true,
  33.             'captcha'    => array(
  34.                 'captcha' => 'Figlet',
  35.                 'wordLen' => 5,
  36.                 'timeout' => 300
  37.             )
  38.         ));
  39.  
  40.         // Add the submit button
  41.         $this->addElement('submit', 'submit', array(
  42.             'ignore'   => true,
  43.             'label'    => 'Sign Guestbook',
  44.         ));
  45.  
  46.         // And finally add some CSRF protection
  47.         $this->addElement('hash', 'csrf', array(
  48.             'ignore' => true,
  49.         ));
  50.     }
  51. }

The above form defines five elements: an email address field, a comment field, a CAPTCHA for preventing spam submissions, a submit button, and a CSRF protection token.

Next, we will add a signAction() to our GuestbookController which will process the form upon submission. To create the action and related view script, execute the following:

  1. % zf create action sign Guestbook
  2. Creating an action named sign inside controller
  3.     at application/controllers/GuestbookController.php
  4. Updating project profile '.zfproject.xml'
  5. Creating a view script for the sign action method
  6.     at application/views/scripts/guestbook/sign.phtml
  7. Updating project profile '.zfproject.xml'

As you can see from the output, this will create a signAction() method in our controller, as well as the appropriate view script.

Let's add some logic into our guestbook controller's sign action. We need to first check if we're getting a POST or a GET request; in the latter case, we'll simply display the form. However, if we get a POST request, we'll want to validate the posted data against our form, and, if valid, create a new entry and save it. The logic might look like this:

  1. // application/controllers/GuestbookController.php
  2.  
  3. class GuestbookController extends Zend_Controller_Action
  4. {
  5.     // snipping indexAction()...
  6.  
  7.     public function signAction()
  8.     {
  9.         $request = $this->getRequest();
  10.         $form    = new Application_Form_Guestbook();
  11.  
  12.         if ($this->getRequest()->isPost()) {
  13.             if ($form->isValid($request->getPost())) {
  14.                 $comment = new Application_Model_Guestbook($form->getValues());
  15.                 $mapper  = new Application_Model_GuestbookMapper();
  16.                 $mapper->save($comment);
  17.                 return $this->_helper->redirector('index');
  18.             }
  19.         }
  20.  
  21.         $this->view->form = $form;
  22.     }
  23. }

Of course, we also need to edit the view script; edit application/views/scripts/guestbook/sign.phtml to read:

  1. <!-- application/views/scripts/guestbook/sign.phtml -->
  2.  
  3. Please use the form below to sign our guestbook!
  4.  
  5. <?php
  6. $this->form->setAction($this->url());
  7. echo $this->form;

Note: Better Looking Forms
No one will be waxing poetic about the beauty of this form anytime soon. No matter - form appearance is fully customizable! See the decorators section in the reference guide for details.
Additionally, you may be interested in our tutorial on form decorators.

Note: Checkpoint
Now browse to "http://localhost/guestbook/sign". You should see the following in your browser:



Create a Model and Database Table

Comments

The code doesn't work as implemented using ZF 1.10 because accessing the questbook controller generates a 404.
questbook? I think you mean 'guestbook'
I created this project from the Windows 7 command line and got to the point where the databases were successfully created and the guestbook page worked fine. When clicked on 'Sign Our guestbook', I got the following error message:

Fatal error: Class 'Application_Form_Guestbook' not found in C:\Program Files\Zend\Apache2\htdocs\zendexamplecmd\application\controllers\GuestbookController.php on line 21

although the class 'Application_Form_Guestbook' was definitely in application\forms\Guestbook.php

I opened Zend Studio and created a project using File->New->Example...->Zend Framework->Create project at existing location (from existing source), and navigated to the location of the folder created with zf from the command line. It added a few files and changed some (e.g. the class 'Application_Form_Guestbook' in application\forms\Guestbook.php is called 'Default_Form_Guestbook' now).

Everything works fine now, including the Sign action. I know it is not really a solution as the project should work without Zend Studio as well, but it solved the problem.
I created this project in Ubuntu 9.10. So far all was working. After adding the guestbook and want to open it in the browser I got the following error message:

Please use the form below to sign our guestbook!
Fatal error: Call to undefined function ctype_space() in /var/www/quickstart/library/Zend/Text/Figlet.php on line 467

I checked /application/controllers/GuestbookController.php, because I thought I come from there, but all is ok.

I would be happy if anyone can help me to solve this error.
Hi,
I just fixed the error. 'ctype' was not installed. So I installed it.
This tutorial is just broken in so many places.

Either fix the code or rewrite the tut.
I got the same issue as Zsolt Molnar, but I don't have Zend Studio to "fix this".

Here is the error.

Fatal error: Class 'Application_Form_Guestbook' not found in /Applications/MAMP/htdocs/quickstart/application/controllers/GuestbookController.php on line 15

I also verified that the class 'Application_Form_Guestbook' was definitely in application\forms\Guestbook.php

I am running this on the 1.10 framework.
Tried to get this working on a clean Zend Server & Zend Studio setup for about 30 minutes, now fighting with

Fatal error: Call to a member function search() on a non-object in C:\Program Files (x86)\Zend\ZendServer\share\ZendFramework\library\Zend\Tool\Project\Provider\Form.php on line 70

and just lost it. If you cant keep the quickstart guide working either the tests are bad, the features evolve too fast/uncontrolled or something else is just way off. How should someone consider the serious integration and usage of ZF if he needs to debug even at the very basic steps you try to guide him through?

Well maybe i ll find some time left to debug the errors and contribute the fixes but for now i just give up. That alone saddens me as i was really looking forward to the experience.
It seems in this case you have to declare the module used to be able to load it. As said in a comment in the previous step in this tutorial. Add to the Bootstrap.php at the end of _initDoctype:

$loader = new Zend_Loader_Autoloader_Resource (array (
'basePath' => APPLICATION_PATH,
'namespace' => 'Application',
));

Now you can use the loader to set your modules for the current namespace:

$loader -> addResourceType ( 'model', 'models', 'Model');
$loader -> addResourceType ( 'form', 'forms', 'Form');

Now you will be able to load the forms in the sign page. This also explains the solution from Zsolt Monar posted above. If no namespace is loaded by the autoloader then zend will fallback to the default namespace. Renaming the form and model class to Default_ would work as well.
I did the tutorial on Fedora 12 using Netbeans 6.9 (M1) Zend integration. All works just fine. Thanks for the tutorial!

+ Add A Comment

If you have a JIRA/Crowd account, we suggest you login first before commenting.
  • BBCode is allowed in the comment markup


  • Select a Version

    Languages Available

    Components

    Search the Manual