Clear Form Data in ZF2

Published on February 24, 2013 by

Several people have asked how to clear a form in Zend Framework 2. In Zend Framework 1, there was the reset method on the Zend_Form class. In ZF2, one would think that the populateValues or setData methods would work when passing an empty array.

However, as you might suspect, it does not. Instead, one can pass in an array of key/value pairs; the key is the name of the element and the value is the element’s new value. If we wanted to clear the value of a username element, this could be accomplished with the code below.

$form->setData(array('username' => ''));

This is convenient if you want to reset the value of a single or a few elements. However, if you want to reset all elements, then it is not as convenient as in ZF1 because one has to add every form element to the array and maintain the correct element names according to the form class. An alternative is to loop through the form’s elements. Consider the code below.

$elements = $form->getElements();

foreach ($elements as $element) {
	if ($element instanceof \Zend\Form\Element\Text) {
		$element->setValue('');
	}

	// Other element types here
}

Above, we are looping through the form’s elements. The reason why there is a check for the type of element is because otherwise, a submit button’s value would be removed as well, for instance. This could of course be overwritten afterwards, but chances are that different form elements would have to be treated differently with this approach anyways.

I have not spent much time trying to find better ways of doing this, so if you know of a more convenient way to go about it, please leave a comment. But if you have been stuck with this problem, then this will at least serve as a starting point. An alternative is to simply redirect back to the same page after form submission such that the form will be in its initial state (usually without data). A method for indicating which status message to display to the user can then be used, such as sessions (namely the FlashMessenger) or URL parameters. Otherwise simply instantiating the form anew is a viable option as per Mike Kelly’s comment, although that does require you to add any dynamic data to the form again (e.g. data that is fetched from the database).

Featured

Learn Zend Framework today!

Take an online course and become a ZF2 ninja!

Here is what you will learn:

  • Understand the theory of Zend Framework in details
  • How to implement an enterprise-ready architecture
  • Develop professional applications in Zend Framework
  • Proficiently work with databases in Zend Framework
  • ... and much more!
Zend Framework logo
Author avatar
Bo Andersen

About the Author

I am a back-end web developer with a passion for open source technologies. I have been a PHP developer for many years, and also have experience with Java and Spring Framework. I currently work full time as a lead developer. Apart from that, I also spend time on making online courses, so be sure to check those out!

7 comments on »Clear Form Data in ZF2«

  1. majid

    Thanks for your post , but a more important problem is “captcha” and remove old captcha session,
    I’ve written this to do so:

    
    foreach($_SESSION as $key=>$val) if(preg_match('/^(Zend_Form_Captcha)/',$key)==true)unset($_SESSION[$key]);
    
    

    but i’m looking for any better way…

    • Andy

      Hello majid and thank you for your comment.

      I have not yet used the captcha element, so there may be better ways of doing that. But assuming that we are talking about Zend Framework 2, you could use the Zend\Session\Container class instead of the $_SESSION superglobal directly. Something like the below, for instance.

      
      $container = new \Zend\Session\Container();
      unset($container->Zend_Form_Captcha);
      
      

      Or if you wish to use the $_SESSION superglobal:

      
      unset($_SESSION['Zend_Form_Captcha']);
      
      

      There is no need to loop through the session keys. You may have to tweak the above examples if the key is placed elsewhere in the session.

  2. Mike Kelly

    Another solution to Bo’s original question might simply be to fetch a fresh copy of the form to pass to the ViewModel.

    
    // module/Album/src/Album/Controller/AlbumController.php:
    
    //...
    use Zend\Mvc\Controller\AbstractActionController;
    use Zend\View\Model\ViewModel;
    use Album\Model\Album;          // <-- Add this import
    use Album\Form\AlbumForm;       // get('submit')->setValue('Add');
    
            $request = $this->getRequest();
            if ($request->isPost()) {
                $album = new Album();
                $form->setInputFilter($album->getInputFilter());
                $form->setData($request->getPost());
    
                if ($form->isValid()) {
                    $album->exchangeArray($form->getData());
                    $this->getAlbumTable()->saveAlbum($album);
    
                    // Re show original page with fresh copy of form
                    $form = new AlbumForm();
                }
            }
            return array('form' => $form);
        }
    
    
    • Hello Mike,

      Thank you very much for your comment. That approach makes perfect sense in situations where you want to reset all of the form’s data. You do need to add dynamic data to the form again, such as data loaded from a database in a select element. That is, however, trivial.

      Thank you again for your solution.

  3. Iván

    Another easy and fast solution:

    
    $data = $this->getRequest()->getPost();
    $emptyData = array_fill_keys(array_keys((array)$data), '');
    
    $form->setData($emptyData);
    
    
  4. Renan

    Hi, It Worked just fine with my Element\Select Fields.
    Thank you!

    • You’re welcome – glad it worked out for you! :-)

Leave a Reply

Your e-mail address will not be published.