开发者

Nesting forms in CakePHP

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

What I'm tryin开发者_如何学Cg 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**.


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.


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...

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜