0
votes

I have a Post model and Tag model which are both set up correctly with a HABTM relationship. I also have a table in my database called posts_tags which is named correctly as per the naming conventions.

However, I can't for the life of me work out how to save tags along with a post. On my "Add Post" page I have this:

<?php echo $this->Form->create('Post'); ?>
<?php echo $this->Form->input('Post.title'); ?>
<?php echo $this->Form->input('Post.body'); ?>
<?php echo $this->Form->input('Tag.name'); ?>
<?php echo $this->Form->input('Post.slug'); ?>
<?php echo $this->Form->end('Publish'); ?>

which calls this action on submit:

public function add() {
    if($this->request->is('post')) {            
        if($this->Post->saveAll($this->request->data)) {
            $this->Session->setFlash('Post published!');
            $this->redirect('/');
        } else {
            $this->Session->setFlash('Post unable to be saved!');
        }
    }

    $this->set('pageTitle', 'Compose new blog post');
}

The post saves but not the tag or the relationship between the post and tag, and Cake gives me no error or warning. What do I have to do to get Cake to save the tag along with the post and make the required relationship?

Edit: here's a dump of what's in $this->request->data which is being saved to the database using saveAll():

array(
    'Post' => array(
        'title' => 'Blog post',
        'body' => 'Testing this post',
        'slug' => 'Blog-post'
    ),
    'Tag' => array(
        'name' => 'test-tag'
    )
)
1
does the tag save in your tags table?Ross
Nope, neither the tag nor the relationship in posts_tags.James Dawson
I've edited the question to give you the output of $this->request->data.James Dawson

1 Answers

0
votes

If your relationship for Tag to Post is hasMany, try changing:

<?php echo $this->Form->input('Tag.name'); ?>

to

<?php echo $this->Form->input('Tag.0.name'); ?>