Satu Sultana
Satu Sultana

Reputation: 537

How to add default value in cakephp select option?

I want to add default select option in input field For example if I right this code

echo $this->Form->input('field', array(
    'options' => array(1, 2, 3, 4, 5),
    'empty' => '(choose one)'
));

I want to change this code like

echo $this->Form->input('field', array(
    'options' => array(1, 2, 3, 4, 5),
    'default' => options[1];  // it's not correct, I just want to add 2 as a default value.
));

Here I want to add option 2 as a default value.

Upvotes: 1

Views: 5703

Answers (4)

Hatem Mahmoud
Hatem Mahmoud

Reputation: 9

 $this->Form->control('name',['options' => $agents,'name'=>'name' ,'empty' => 'choose one','required']);

Upvotes: 0

drmonkeyninja
drmonkeyninja

Reputation: 8540

The issue is with the PHP you've written. You're attempting to reference something that doesn't exist for your default and isn't a proper PHP variable:-

echo $this->Form->input('field', array(
    'options' => array(1, 2, 3, 4, 5),
    'default' => options[1];  // it's not correct, I just want to add 2 as a default value.
));

options[1] is not a valid PHP variable as you're missing the $ symbol and the $options array hasn't been defined. You've just passed an array to the options attribute of your input.

You need to define the $options array first and then pass that to $this->Form->input() like this:-

$options = array(1, 2, 3, 4, 5);
echo $this->Form->input('field', array(
    'options' => $options,
    'default' => $options[1]; // '2' in the defined array
));

Upvotes: 2

Pradeep Singh
Pradeep Singh

Reputation: 1290

You can try this

$options = array(1, 2, 3, 4, 5);
$attributes = array('value' => 2, 'empty' => false);
echo $this->Form->select('field', $options,$attributes);

This is the link from cookbook

and if you are fetching result from database and then populating in select option then just put the value in $this->request->data['Model']['field'] = 'value'; in controller and it will be default value in select dropdown

Upvotes: 1

Salines
Salines

Reputation: 5767

Read Book

echo $this->Form->input('field', array(
    'options' => array(1, 2, 3, 4, 5),
    'default' => '2'
));

Upvotes: 1

Related Questions