Vael Victus
Vael Victus

Reputation: 4122

Passing PHP array to CakePHP's form helper

I've sent arrays to CakePHP like this in the past:

$this->Form->input("Req.{$i}");

I've manually put {$i} in which is derived from the code itself in a loop. Ideally I wanted to put in something like Req.{} to generate the next key index, but it seemed only manually putting it in would work. Years later I need to have something like

$this->Form->input("Req.{$i}.list.{}");

And I'd like to avoid generating an {$i2}. Basically, I'm asking how to properly send multi-dimensional arrays to $this->request->data on POST, without having to specify an index name, much like we might have <input name='whatever[]'> in traditional PHP. I'm posting with jQuery AJAX, if that matters.

Update: Following drmonkeyninja's answer, I received

[list] => Array(
                            [0] => Array
                                (
                                    [name] => 
                                )

                            [1] => Array
                                (
                                    [value] => 
                                )

                            [2] => Array
                                (
                                    [req] => 
                                )
                 )

It seems it will be required that I make an $i2 as PHP/HTML have no way of knowing that I'm not trying to make a new array for each entry.

Upvotes: 0

Views: 95

Answers (1)

drmonkeyninja
drmonkeyninja

Reputation: 8540

Normally in CakePHP you define the array path separating array indexes using .:-

$this->Form->input('Model.0.value'); // name="data[Model][0][value]"

If you don't want to specify a numerical index you can just use .. to represent an empty index:-

$this->Form->input('Model..value'); // name="data[Model][][value]"

Update

If you can't get the CakePHP array path syntax working in the way you need you can always manually set the input names in the input options:-

$this->Form->input('Model..value', ['name' => 'data[Model][][value]']);

Upvotes: 1

Related Questions