tags:

views:

113

answers:

2

I am wondering if there's a way in CakePHP to nest multiple models in a form?

What I'm trying to accomplish is to make a form for creating Posts that will also contain fields for adding Images (separate model) that will automatically be connected to the created post.

Something similar to Ruby on Rails ** accept_nested_attributes_for**.

A: 

I'm quite sure there's no CakePHP compliant way to do this. I suggest you to write just one big form and parse the content in the controller after the request...

Enrico Carlesso
+1  A: 

If I understand you correctly, this can absolutely be done (see: Saving Related Model Data in the official documentation). Assuming Post hasMany Image and Image belongsTo Post, you'd set it up in the following way.

In your view, you'd create a Post creation form like so:

<?php
    $form->create("Post", array('action'=>'add','type'=>'file'));
    $form->input("Post.title");
    $form->input("Post.body");

    $form->input("Image.0.upload", array('type'=>'file', 'label'=>__('Attach an image:',true));
    $form->input("Image.1.upload", array('type'=>'file', 'label'=>__('Attach an image:',true));
?>

This defines a quick and dirty form that renders Post.title and Post.body fields, and two file-attachment widgets for two new Images.

Then, in your posts_controller.php:

class PostsController extends AppController
{
    /* stuff before PostsController::add() */

    function add()
    {
        if (!empty($this->data)) {

            if ( $this->Post->saveAll( $this->data, array('validate'=>'first'))) {
                $this->flash(__("Post added.",true), 5);
            }
        }
    }

    /* Stuff after PostsController::add() */
}

Assuming your Post and Image data validates, this will save a new Post, then save the two Images, simultaneously and automatically associating the new Image records with the new Post record.

Daniel Wright
Thank you! That was exactly what I was looking for. Best regards
Erik
if so, you should vote up and accept the answer!
Daniel Wright