Search code examples
cakephp-1.3formhelpermultiple-records

using the form helper for multilpe records


I have a table called specs. I need to edit multiple rows from it in one form and save it at once.

// table structure
specs [id, name, value, owner_id]
// controller part
$data = $this->Spec->find('all'); // skipping the conditions and other sub-code
$data = set::combine(...);
/*
result, keyed using the spec[id] column.
array (
  [3] = array(id=>...),
  [22] = array(id=>...)
)
*/

Now I'm not sure how to continue. I know how to build a form ready to CREATE new multiple records(Model.{n}.fieldname), but how can i create an "edit" form that will allow the saveAll()?

trying to iterate through the result array gets the form close.. but i can't see the values of fields in the input elements..


Solution

  • You can try this:

    In the controller:

    public function edit() {
        $products = $this->Product->find('all');
        if (!empty($this->data)) {
            if ($this->Product->saveAll($this->data['Product'])) {
                $this->Session->setFlash('ok');
            } else {
                $this->Session->setFlash('not ok');
            }
        } else {
            $this->data['Product'] = Set::extract($products, '{n}.Product');
        }
        $this->set(compact('products'));
    }
    

    In the view:

    echo $this->Session->flash();
    
    echo $this->Form->create('Product');
    
    foreach ($products as $i => $product) {
        echo $this->Form->input("$i.id");
        echo $this->Form->input("$i.name");
    }
    
    echo $this->Form->end('Save');
    

    PS: I think you can adapt my Product example to your needs can't you? : )