March 24, 2010

How to Save Multiple Models in CakePHP

It’s inevitable that you will have a form where you will need to save multiple models at once. Here is a small hack on how you might do that.

if (!empty($this->data)) {
    $this->ModelName->create();
    $allSaved = true;
 
    foreach($this->data as $model => $data) {
        switch ($model) {
            case 'ModelName1' :
                /*manipulate ModelName1 data here*/
                if (!$this->ModelName1->saveAll($this->data['ModelName1']))
                    $allSaved = false;
                break;
            case 'ModelName2' :
                /*manipulate ModelName2 data here*/
                if (!$this->ModelName2->saveAll($this->data['ModelName2']))
                    $allSaved = false;
                break;
        }
    }
 
    if ($allSaved) {
        /*Print Success Message*/
    }
}

Leave a comment