cakePHP value for empty option

22k views Asked by At

is there a way to pass a value for the empty option in a select dropdown generated by the FormHelper?

I'm creating an input like this:

echo $this->Form->input('supplier_id', array('empty'=>true));

with values supplied automatically from the controller like this

$suppliers = $this->Product->Supplier->find('list');
$this->set(compact('suppliers'));

and the select box is created like this:

<select name="data[Product][supplier_id]" class="form-control" id="ProductSupplierId">
  <option value=""></option>
  <option value="1">Lolë Montreal</option>
  <option value="2">Spiritual Gangster</option>
  <option value="3">Havaianas</option>
</select>

but I would like the first option (the empty one) to have a value of 0 instead of '' is it possible? or should I instead modify the $suppliers array in the controller with something like

$suppliers[0] = '';

and remove the empty option from the FormHelper input?

4

There are 4 answers

0
mark On BEST ANSWER

Using the verbose array syntax you can chose any value for empty:

echo $this->Form->input('supplier_id', ['empty' => ['0' => '']]);

See http://www.dereuromark.de/2010/06/23/working-with-forms/

0
Soubhagya Kumar Barik On

All the above will work but, if you want to validate field through model then you need to use this

  <?= $this->Form->control('supplier_id', ['options' => $suppliers, 'empty' => '--Select--']) ?>
0
burunoh On
echo $this->Form->input('supplier_id', array('empty'=>'Select'));

You can also add required to it:

echo $this->Form->input('supplier_id', array('empty'=>'Select', 'required' => true));
0
TommyDo On

In cakephp 3.x you will get troubles with this...

It will be like

Select
0
   value1
   value2
   value3
   ...

So I fixed it by:

  • In controller:

    ...something to get data from database

    $data_init = ['0'=>'Select'];

    $data = $data_init + $query->toArray();

    $this->set( '$list', $data);

  • In view:

    'options' => $list,

And the list will be like:

Select
value1
value2
value3
...