user3573535 user3573535 - 1 month ago 6x
PHP Question

Cakephp2 - Creating Form from loop

I have translates table with example data:

enter image description here

So, this table holds records, which will represent custom translation texts.

Now i want to build a form to edit all of those rows in one page / form.

This is controlle code:

public function translate() {
$data = $this->Translate->find('all');
$this->set('data', $data);

pr ($this->request->data);

if ($this->request->is('post','put')) {

if ($this->Translate->save($this->request->data)) {
$this->Session->setFlash('Recipe Saved!');
return $this->redirect($this->referer());

And view - please note, that i have used loop for creating inputs, not sure if cakephp has better way to do this.

<?php echo $this->Form->create('Translate'); ?>
foreach ($data as $d) {
echo $this->Form->input('text', array('label' => 'Link strony', 'type' => 'text','value'=>$d['Translate']['text']));
echo $this->Form->input('id', array('type' => 'hidden', 'value' => $d['Translate']['id']));
<?php echo $this->Form->end(array('class' => 'btn btn-success floatRight', 'label' => 'Zapisz')); ?>

For now, this code works, but not as i expect.
shows only last input, ignoring other ones. Attached, you see debug of $this->request->data. Only last item is edited. All i want is to have ability to edit selected input and save. Thanks for help.

enter image description here


Looks like you're saving multiple rows in a single form. In that case, you need to change your approach a bit.

  1. Use proper indices in the Form helper.
  2. Use saveAll() instead of save() to save multiple data.

Changes to the View file:

       foreach ($data as $k => $d) {
           echo $this->Form->input('Translate.'.$k.'.text', array(
            'label' => 'Link strony', 
            'type'  => 'text',
            'value' =>$d['Translate']['text']

           echo $this->Form->input('Translate.'.$k.'.id', array(
               'type'  => 'hidden', 
               'value' => $d['Translate']['id']

And then, in your controller:

if ($this->request->is('post','put')) {


      /* Other code */