CakePHP value for empty option

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

I create an input like this:

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

with values ​​automatically added from the controller

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

and the selection field is created as follows:

 <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 (empty) to have a value of 0 instead of ``, is this possible? or should I change the $suppliers array in the controller with something like

 $suppliers[0] = ''; 

and remove the empty option from FormHelper input?

+6
source share
3 answers

Using the detailed array syntax, you can select any value for the empty one:

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

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

+12
source
 echo $this->Form->input('supplier_id', array('empty'=>'Select')); 

You can also add the required one to it:

 echo $this->Form->input('supplier_id', array('empty'=>'Select', 'required' => true)); 
+1
source

In cakephp 3.x you get problems with this ...

It will be like

 Select 0 value1 value2 value3 ... 

So I fixed it:

  • In the controller:

    ... something to get data from the database

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

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

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

  • In sight:

    'options' => $ list,

And the list will look like this:

 Select value1 value2 value3 ... 
0
source

Source: https://habr.com/ru/post/953654/


All Articles