0

Is there a way to "automagically" add the empty option to a drop down list?

What I'm looking for is to add this option on a drop down list of a belongTo relation that can be null, without having to add code on the view.

I do believe this should be a Model option, that could be useful for example on a scaffold.

jplfl
  • 82
  • 11
  • 1
    whats wrong with `empty` option in the view for the Form helper method? – mark Sep 11 '12 at 10:49
  • nothing, I'm just looking to see if this automation exists – jplfl Sep 11 '12 at 10:53
  • you can create array in controller to handle this issue – Moyed Ansari Sep 11 '12 at 12:31
  • @moyed truth, but not automatic – jplfl Sep 11 '12 at 14:21
  • You can set it via the form defaults when you use `FormHelper::create()` using the `inputDefaults` key. If this is something you use across your app you can alias the FormHelper and override the create method to always include this. http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html#options-for-create – jeremyharris Sep 11 '12 at 16:08

1 Answers1

0

You could override the _findList method or make a new custom find and use _findList (call it say _findSelectList). Example:

protected function _findList($state, $query, $results = array()) {
    $return = parent::_findList($state, $query, $results);
    if ($state === 'after') {
        $return = array('' => 'select one') + $return;
    }
    return $return;
}

Or you could extend FormHelper and add the empty option there by default which I think would be simpler. You may actually be able to get away with setting empty in inputDefaults when calling $this->Form->create('Model', array('inputDefaults' => array('empty' => 'Select One')));. If this works and you don't want to do it in every form, extend FormHelper and set this as the default in it.

tigrang
  • 6,767
  • 1
  • 20
  • 22
  • so the response is no, CakePHP doesn't treat these case out of the box. I'm accepting your answer since you took the time to enumerate several ways of doing it. Thanks! – jplfl Sep 12 '12 at 08:54