phpcakephpform-helperscakephp-3.2

CakePHP 3 : dynamically create options in select | Form Helper


I want to generate select input field like

<select name="quantity">
  <option value="">Quantity</option>
  <option value="1">1</option>
  <option value="2">2</option>
  <option value="3">3</option>
</select>

where option is generated dynamically.

There is a stock column which contains int value. I want to generate options as much as value in stock. Ex: If stock value is 5 then option will be from 1 to 5.

I can generate select input field by

$this->Form->select('quantity', [1,2,3,4,5], ['empty' => 'Quantity'])

But here options generated will of 5 length. I want it to be generated as per the value in stock column.


Solution

  • First set your $stack variable value in controller using set (Simple way) :

     $this->set('stack', $stack);
    

    use that variable like this in your view:

    $options = range(1,$stack);
    
     $this->Form->select('dropdown name', $options, ['empty' => 'Quantity'])