Thomas John
Thomas John

Reputation: 1899

cakephp : how to get an array of elements from a web form

In my cakephp form I have following code

<p> <?php echo $form->input('option[]',array('size'=>13)); ?> </p>
<p> <?php echo $form->input('option[]',array('size'=>13)); ?> </p>
<p> <?php echo $form->input('option[]',array('size'=>13)); ?> </p>
<p> <?php echo $form->input('option[]',array('size'=>13)); ?> </p>

I am trying to get values from a set of input text boxes, the number of text boxes can be set by the user, so cant give individual names of each text box, but How can I get values from my controller to insert data to db table

Thank you

Upvotes: 3

Views: 6131

Answers (3)

Nik Chankov
Nik Chankov

Reputation: 6047

You can leave the form as it is (and use suggestions from @Wizzard and @Lee), but the best practice is to use an incrementing variable to construct the list. i.e.:

for($i=0;$i<$option_number;$i++){
   echo $form->input("MyModel.{$i}.option");
}

This way your variable after posting the form will look like:

data[MyModel][0][option] = 'the value' dataMyModel[option] = 'the value' data[MyModel][2][option] = 'the value' ... and so on...

In the controller you can access the posted data by:

print_r($this->data);

Take a look saveAll() (search for saveAll in your browser and look for suggested data structure)

Upvotes: 3

Lee
Lee

Reputation: 13542

your input fields are all named the same thing: option[]. This is good. It causes php to automatically turn them into an array when the request is loaded in. So you can get them in your CakePHP controller like this:

$this->params['form']['option'][0]
$this->params['form']['option'][1]
... and so on ...

Upvotes: 1

Wizzard
Wizzard

Reputation: 12692

Pretty sure they're in the array $this->params['form'] in the controller.. or $this->data

In the method of your controller, do a var_dump($this); and you'll see where they show up

Upvotes: 0

Related Questions