<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Jesus Blog &#187; zend framework multipage forms</title>
	<atom:link href="http://jesus-blog.com/tag/zend-framework-multipage-forms/feed" rel="self" type="application/rss+xml" />
	<link>http://jesus-blog.com</link>
	<description>Jesus-blog.com</description>
	<lastBuildDate>Mon, 30 Apr 2012 08:40:07 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.9.2</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>Zend Framework multi page forms</title>
		<link>http://jesus-blog.com/coding-tips-and-tutorials/zend-framework-multi-page-forms.html</link>
		<comments>http://jesus-blog.com/coding-tips-and-tutorials/zend-framework-multi-page-forms.html#comments</comments>
		<pubDate>Wed, 01 Oct 2008 12:38:28 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Coding Tips and Tutorials]]></category>
		<category><![CDATA[Nathan Whitworth]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[Zend Framework]]></category>
		<category><![CDATA[zend framework multipage forms]]></category>

		<guid isPermaLink="false">http://blog.nathanwhitworth.co.uk/?p=47</guid>
		<description><![CDATA[I&#8217;ve started using Zend Framework for a project I&#8217;m under taking here at TradeDoubler. I&#8217;m building a new part of Searchware that is essentially standalone, so figured that this is a great oportunity to push for framework support. Better form validation, less scope for creating errors in trivial donkey work coding because it&#8217;s already done [...]]]></description>
			<content:encoded><![CDATA[<p>I&#8217;ve started using Zend Framework for a project I&#8217;m under taking here at TradeDoubler. I&#8217;m building a new part of Searchware that is essentially standalone, so figured that this is a great oportunity to push for framework support. Better form validation, less scope for creating errors in trivial donkey work coding because it&#8217;s already done for you, and ultimately a better experience for the user.</p>
<p>The problem I soon discovered with ZF, is that the documentation is not as good as I would of hoped. Their introductory videos are absolutely amazing, but when it comes to getting a real project started, they leave you feeling a bit left out in the cold.</p>
<p><!--adsense--></p>
<p><strong>Multi Page Forms</strong></p>
<p>A good example of this, and something I&#8217;ve just been working on, is multi page forms. Zend Form is a great start and will go places, but right now, I think it&#8217;s not quite there. I discovered that subforms are the recommended way to implement multi page forms, but the example in the documentation again doesn&#8217;t quite explain how to do it, it just points you in a direction and expects you to figure the rest out for yourself. All very good, but some of us are fairly busy and would rather just read a comprehensive example.</p>
<p><strong>A comprehensive example <img src='http://jesus-blog.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </strong></p>
<p>This is how I decided to make a multi page form based on Zend Form subforms. I don&#8217;t know if this is the best way of doing it, and I am a complete newbie to ZF, but since I couldn&#8217;t find any other examples, and this does work, I&#8217;ll just have to presume it is until I&#8217;m corrected by one of you kind readers :p. This example will show you how to setup the required classes, build a simple form, validate, and then store the information and make it available to subsequent forms for decision making.</p>
<p><strong>Note: </strong>This is not a beginners guide to Zend Framework or MVC. If you&#8217;re not quite sure how ZF works, or what MVC is, please check out the <a href="http://framework.zend.com/docs/screencasts" target="_blank">introductory vids</a> on the Zend site. They are very good.</p>
<p>So, to kick things off we&#8217;re going to need to load up all the classes required for our forms. To do this, add the following lines to your boot strap file.</p>
<pre><code>
DEFINE('APPLICATION_PATH','/data/web/yourApplication');

Zend_Loader::loadClass("Zend_Form");
Zend_Loader::loadClass("Zend_Session");
Zend_Loader::loadClass("Zend_Session_Namespace");

// And any validation classes you will be using, for example
Zend_Loader::loadClass("Zend_Validate_NotEmpty");
</code></pre>
<p>This will set up our bootstrap file with everything we need to build a form, so the next job is editing your controller class. Add the following methods into your controller. They are used to store and read validated form values, but more on that later.</p>
<pre><code>
	private function storeFormValues(Zend_Form $form)
	{
		$formSession = new Zend_Session_Namespace('yourAppForm');

		foreach ($form-&gt;getValues() as $key =&gt; $value)
		{
			$formSession-&gt;$key = $value;
		}
	}

	private function getFormValues()
	{
		$formSession = new Zend_Session_Namespace('yourAppForm');

		$data = array();
		foreach ($formSession-&gt;getIterator() as $key =&gt; $value)
		{
			$data[$key] = $value;
		}
		return $data;
	}</code></pre>
<p>You will also need to add the following method in your controller class.</p>
<pre><code>
	 protected function getForm($formName)
	 {
	 	// you will need to edit this later, but leave it for now.
	 	require_once APPLICATION_PATH . '/forms/parentForm.php';

	 	$mainForm = new Form_ParentForm($this-&gt;getFormValues());

	 	if ($formName == 'main')
	 	{
	 		$form = $mainForm;
	 	}
	 	else
	 	{
	 		$form = $mainForm-&gt;getSubForm($formName);
	 		$form-&gt;addElement('hidden','currentFormStage',array('value' =&gt; $formName));
	 	}

	 	return $form;
	 }
</code></pre>
<p>So, I&#8217;ll take a little time to explain that one since it&#8217;s not instantly obvious.</p>
<p>First off</p>
<pre><code>require_once APPLICATION_PATH . '/forms/parentForm.php';</code></pre>
<p>is the path to your form classes. I&#8217;ll explain how to create those later but for now, decide where you will want to store your forms, and point this there. Remember the constant APPLICATION_PATH was set in the bootstrap file.</p>
<p>The next line is</p>
<pre><code>$mainForm = new Form_AddAccount($this-&gt;getFormValues());</code></pre>
<p>This instantiates our parent form and passes to it any form data we have in our session.</p>
<p>The next part is</p>
<pre><code>if ($formName == 'main')
{
	$form = $mainForm;
}</code></pre>
<p>This is used later on in the controller to check whether the entire form (i.e. all of it&#8217;s sub pages are validated). The controller asks for the sub form name, but if this is &#8216;main&#8217;, then the parent class is sent back.</p>
<p><strong>Creating our forms</strong><br />
So far we&#8217;ve built the required scaffolding for our multi page form that will be used by the controller. The next step is to create the forms themselves. As I&#8217;ve already mentioned the overall multi page form consists of a parent container form, and a collection of sub forms. For the sake of making it easy to read, I&#8217;m going to use VERY crude examples of forms, but please consult the Zend Form docs for more details about creating various form elements. That part of things is fairly well documented.</p>
<p>The entire parent class looks like this&#8230;</p>
<pre>
<code>
class Form_ParentForm extends Zend_Form
{
	private $formValues;

	public function __construct($formValues)
	{
		$this->formValues = $formValues;
		parent::__construct();
	}

	public function getFormValue($name)
	{

		if (isset($this->formValues[$name]))
		{
			return $this->formValues[$name];
		}
		else
		{
			return null;
		}

	}

	public function init()
	{

		$this->setAction('index');
		$this->setMethod('post');

		require_once APPLICATION_PATH . '/forms/SubFormPageOne.php';
		require_once APPLICATION_PATH . '/forms/SubFormPageTwo.php';

		$pageOne = new Form_SubFormPageOne($this);
		$pageTwo = new Form_SubFormPageTwo($this);

		$this->addSubForm($pageOne,'pageOne');
		$this->addSubForm($pageTwo,'pageTwo');

	}

}
</code>
</pre>
<p>The only bit you need to be concerned about editing here is the init() method. Change setAction() and setMethod() as you see fit, but they will probably be ok as they are in most cases.<br />
The next bit, the requires, is important. Remember in the controller class we edited the getForm() method. There was an include path in there that pointed to the parent form. You need to make sure that, obviously, this parent form is saved to the same place. You could put the subforms in other directories, but I don&#8217;t see any benefit of doing so, so I&#8217;d recommend you keep then all bundled together in the same directory.</p>
<p>Once you have included then, you instantiate the subforms (actually, they are instances of Zend_Form and not SubForm, but that is ok), and then pass them to addSubForm. Hopefully this is quite easy to follow so I&#8217;m not going to explain it any further. If you get stuck, please feel free to ask me a question.</p>
<p>So then, our final step in building the forms is to create the sub forms. The subform class looks like this.</p>
<pre>
<code>
class Form_SubFormPageOne extends Zend_Form
{
	private $parentForm;

	public function __construct(Zend_Form $parentForm)
	{
		$this->parentForm = $parentForm;
		parent::__construct();
	}

	public function init()
	{

		// engine dropdown
		$engineSelect = $this->createElement('select','engine');

		$engineSelect->addMultiOption('','Please Choose...');
		$engineSelect->addMultiOption('google','Google');
		$engineSelect->addMultiOption('yahoo','Yahoo');
		$engineSelect->addMultiOption('msn','MSN');

		$engineSelect->setRequired(true);

		$this->addElement($engineSelect);

		// create submit button
		$this->addElement('submit', 'btnNext', array( 'label' => 'Next'));

	}

}
</code>
</pre>
<p>Apart from changing the class name to suit your needs, the only other thing you should need to edit is the init() method. In here you create the form elements, apply validation, decorators and so on. This work in exactly the same way as a single page form, so please consult one of the many Zend Form examples for details on adding elements. As you can see our example form simply gives a dropdown list of search engines and a submit button.</p>
<p><strong>Plugging it all together</strong><br />
So we&#8217;ve got our scaffolding, and we&#8217;ve got our forms. The only thing left to do now is to stick it all together, and this happens in the &#8216;action&#8217; method of the controller. In most cases, and certainly this one, it will be the index action.</p>
<p>This method is a bit longer than the others so rather than me blabbering on here, I&#8217;ll let the comments to the talking. <img src='http://jesus-blog.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<pre>
<code>
public function indexAction()
{
	$request = $this->getRequest();

	// is this a post back, i.e was the form submitted or is it a first visit.
	if ($request->isPost())
	{
		/*
		Get an instance of the current form.
		Remember currentFormStage was appended
		to the form as a hidden field in the getForm method.
		*/
		$form = $this->getForm($_POST['currentFormStage']);

		// does is pass validation?
		if ($form->isValid($_POST))
		{
			// yes, so save the values to our session.
			$this->storeFormValues($form);

			/*
			So, we've just check a subform and it was valid.
			Does this now make our entire form collection valid?
			Let's check by getting in instance of the parent form.
			*/
			if ($this->getForm('main')->isValid($this->getFormValues()))
			{
				/*
				The form is complete, so redirect to the
				finish action (you will need to create this)
				*/
				$this->_redirect("index/finish");
			}

			/*
			A crude but workable method of choosing which form to go to next.
			*/
			switch ($_POST['currentFormStage'])
			{
				case 'pageOne':
					$newForm = 'pageTwo';
					break;
				default:
					$newForm = 'pageOne';
				break;
			}
			/* get an instance of our new form.
			having passed page one, this would be now page two.
			*/
			$form = $this->getForm($newForm);

		}

	}
	else
	{
		/*
		If this is the first time the page is loaded
		i.e. no forms submitted, let's make sure the session is
		empty.
		*/
		$formSession = new Zend_Session_Namespace('yourAppForm');
		$formSession->unsetAll();

		// and then load the first form page.
		$form = $this->getForm('pageOne');
	}

	$this->view->printForm = $form;

}
</code>
</pre>
<p>And there it is, you&#8217;re done. You have a working multi page form in the Zend framework. One final note, the last line $this->view->printForm = $form; is simply to pass the form to the view. The view file for this controller/action, would contain <?= $this->printForm; ?></p>
<p>I hope that helped clear things up, and if anybody has any questions, please feel free to post them.</p>
<p><!--adsense--></p>
]]></content:encoded>
			<wfw:commentRss>http://jesus-blog.com/coding-tips-and-tutorials/zend-framework-multi-page-forms.html/feed</wfw:commentRss>
		<slash:comments>11</slash:comments>
		</item>
	</channel>
</rss>

