Setting an Element’s Default Value

Published on July 20, 2012 by

In forms you will often want to set the default values of elements. This can easily be accomplished in Zend Framework by using the setValue method like so:

$select = new Zend_Form_Element_Select('myselect');
$select->setMultiOptions(array(
	-1 => 'Gender',
	0 => 'Female',
	1 => 'Male'
))->setValue(1); // Set default to 1
				
$this->addElement($select);

However, the above can also be accomplished by using the setDefaults method of the Zend_Form class by passing an array of element IDs and their desired default values. This leads us to the main purpose of this article. Logically, it would be feasible to think that this could be done like shown below.

$select = new Zend_Form_Element_Select('myselect');
$select->setMultiOptions(array(
	-1 => 'Gender',
	0 => 'Female',
	1 => 'Male'
));

// Set defaults for an array of elements. Key = element ID. Value = default value
$this->setDefaults(array(
	'myselect' => 1
));
				
$this->addElement($select);

Surprisingly, this will not work!. This is because the setDefaults method call has to be after the element is added to the form. This is something that most people are likely to find illogical. Apparently the Zend Framework is very strict regarding the order of which statements are executed. It would probably make more sense if all of the elements’ properties were added before the elements were added to the form.

Instead, the below will work as intended.

$select = new Zend_Form_Element_Select('myselect');
$select->setMultiOptions(array(
	-1 => 'Gender',
	0 => 'Female',
	1 => 'Male'
));
				
$this->addElement($select);

// Set defaults for an array of elements. Key = element ID. Value = default value
$this->setDefaults(array(
	'myselect' => 1
));

Hopefully this helps people who have faced this problem. Due to its illogical nature, it can be a quite difficult problem to solve as it is probably not the first thing a programmer considers to be wrong in this case.

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!

One comment on »Setting an Element’s Default Value«

  1. Shaggy

    Thanks :)

Leave a Reply

Your e-mail address will not be published.