Tuesday, March 26, 2013

How to render a select box with Zend Framework forms.

I was using Zend Framework 2 to make a quick form when I needed to render a quick select box for my user to select a month. I never thought I would be writing a blog post about something PHP related or something as simple as creating a dropdown so that a user could select a month; however, I ran into so much trouble doing so I think it is necessary for me to post my solution for posterity.

I was seriously scouring Google for over a hour; find a proposed solution, test, fail, repeat. The Zend documentation was fairly useless as per usual, so I was left searching random blog entries. Every time I came across something that looked promising I'd see something in the comments resembling the bellow remarks:
READER: This codez doesn't work dude!
AUTHOR: It totes does, you just got to download my custom library add-on first!

Anyway, my luck changed when I stumbled across this blog, it was the first one that had a solution that worked out of the box. However, his method for creating the element differed from the one I had used in the rest of my form. In a sane world this would not have mattered, but, in the real world this happened to make the select box look very different from the rest of the elements in my form. This still gave me a good jumping off point for this solution:

$this->addElement('select', 'Month', array(
      'label' => 'Month',
      'required' => true,
      'multiOptions' => $this->getMonths() ));


Just add an option key called 'multiOptions' and assign it an array where the key is the html value and the value is the html displayed text. Happy coding!

No comments:

Post a Comment