CakePHP: How to update multiple records at the same time with the Form helper

11,778

CakePHP associates all fields with the same 'index' to be a single 'record' in your database. The 'index' (i.e. the 0 in Foo.0.id) does not have any relation to the 'id' of the record, it's just a number.

For example;

Foo.0.id   = 123
Foo.0.name = 'hello';
Foo.1.id   = 124
Foo.1.name = 'world';

As mentioned in the start of my answer, the index itself does not matter, this code will do exactly the same:

Foo.12345.id   = 123
Foo.12345.name = 'hello';
Foo.54321.id   = 124
Foo.54321.name = 'world';

As long as fields of the same record have the same 'index', CakePHP will understand that they belong 'together'.

When submitting this data and saving it using;

$this->Foo->saveMany($this->data['Foo']); // Just $this->data will probably work as well

CakePHP update two rows via the Foo model;

table 'foos';

id     name
------------------------
123    hello
124    world

Your code seems to use the same 'id' ($qset['Qset']['id']) for each row, which is probably not the right ID to update those records

Share:
11,778
emersonthis
Author by

emersonthis

I am a designer, developer, and problem solver. I make websites and stuff. I work with brazen startups, modest individuals, earnest small business, and everyone in between. I care as much about how things look as how they work. I enjoy writing and teaching what I know. The best part about my job is constantly learning new things.

Updated on June 16, 2022

Comments

  • emersonthis
    emersonthis almost 2 years

    On an edit page for the model Test I want to be able to update the "Questions.order" field on all of it's associated (by hasMany) questions from the same form.

    I've ready the Cake book chapter on saveMany()/saveAll() in the book, and I'm using the Model.0.field syntax but I can't figure out how to tell CakePHP which record to corresponds to which input. Should the # in Model.#.field correspond to the question's id field? Here's what I'm currently doing:

     echo $this->Form->create( 'Question', array('action'=>'order'));
    
    $n = 0;
    foreach ($questions_array as $question) : ?>
            <?php echo $this->Form->input('Question.'.$n.'.order' ); ?>
            <?php echo $this->Form->input('Question.'.$n.'.id', array('type'=>'hidden', 'value'=>$question['Question']['id']) ); ?>
            <input type="submit" value="Save" />
    ...
    $n++;
    endforeach;
    $this->Question->Form->end();
    

    The form submits and appears to save, but the updated order values do not correspond to the right question records. What am I doing wrong?

    Update:

    Here is the order action in my controller:

    public function admin_order() {
        $data = $this->request->data;
        $this->Question->saveAll($data['Question']);
        $this->Session->setFlash( "Order saved.");
        $this->redirect( $this->referer() );
    }