Paul
Paul

Reputation: 337

How to insert multiple rows using cakePHP

In the cakePHP project I'm building, I want to insert a defined number of identical records. These will serve as placeholders records that will have additional data added later. Each record will insert the IDs taken from two belongs_to relationships as well as two other string values.

What I want to do is be able to enter a value for the number of records I want created, which would equate to how many times the data is looped during save.

What I don't know is:

  1. how to setup a loop to handle a set number of inserts

  2. how to define a form field in cakePHP that only sets the number of records to create.

What I've tried is the following:

function  massAdd() {
    $inserts_required = 1;
    while ($inserts_required <= 10) {
        $this->Match->create();
        $this->Match->save($this->data);
        echo $inserts_required++;
    }

    $brackets = $this->Match->Bracket->find('list');
    $this->set(compact('brackets'));
}

What happens is:

  1. At the top of the screen, above the doc type, the string 12345678910 is displayed, this is displayed on screen

  2. A total of 11 records are created, and only the last record has the values passed in the form. I don't know why 11 records as opposed to 10 are created, and why only the last records has the entered form data?

As always, your help and direction is appreciated.

Upvotes: 0

Views: 8357

Answers (1)

Aziz
Aziz

Reputation: 917

  1. in your view try to write something like

    echo $form->input('Answer.n.title', array('type'=>text'));
    

    in controller write

    function add(){
        $this->Answer->saveAll($this->data);
    }
    
  2. in my project I used jQuery, to add a new row without reloading a page.

Upvotes: 2

Related Questions