3

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

1
  • checkout saving hasmany association Commented Jul 28, 2015 at 11:29

3 Answers 3

3

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)

Sign up to request clarification or add additional context in comments.

1 Comment

+1 This is, indeed, the correct way to do it. If you want to add the fields before submitting the form, try jQuery append together with this answer.
1

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 ...

1 Comment

print_r($this->params['form']); gives empty values as Array ( )
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.