Monday, November 3, 2008

List displays with a blank option using FormHelper input

I just discovered a super easy way to generate a drop-down choice of related fields in CakePHP1.2.

This code in my controller:


$pagetypes = $this->Contentpage->Pagetype->find('list');
$this->set(compact('pagetypes'));


Coupled with this code in my view:


$form->input('pagetype_id');


Generates a select box with all my Pagetype options filled automagically. In addition, this remains stateful when I return to edit this.

This is such an improvement over older versions of CakePHP and what I've had to done in Ruby on Rails in the past.

One problem that this posed to me was getting a blank field or a field that prompted the user with a "Please select..." message. I knew there had to be a way to do this, so with a little fishing in Google's CakePHP Group, I came upon this answer:

To deliver a simple blank space in the drop-down:


$form->input('pagetype_id', array('empty' => true));

To deliver a "Please Select..." (or whatever you want) in the drop-down:


$form->input('pagetype_id', array('empty' => 'Please Select...'));


That's all there is to it! :)

No comments:

Post a Comment