0
votes

I have built a CakePHP app that allows a user to create posts and add tags (topics) to them. The structure of the database and associations can be seen here: Setting up contains for a join table in CakePHP

I have managed to successfully pull the data out using Contain via the join table. But now I'm trying to build the part where a user enters a topic and then save it BOTH in the Topic Table and the Topic_post table.

I have the following code my add new post method:

if ($this->request->is('post'))
        {
            //$this->Post->create();

            if ($this->Post->save($this->request->data))
            {
                // Save extra data
                $this->Post->saveField('user_id', $this->Auth->user('id'));
                $this->Post->saveField('datetime', date('Y-m-d H:i:s'));
                $this->Post->saveField('modified', date('Y-m-d H:i:s'));
                $this->Post->saveField('status', 1);

                // Build slug
                $post_title = Sanitize::html($this->request->data['Post']['title'], array('remove'=>true, 'quotes' => ENT_NOQUOTES));
                $post_title = String::truncate($post_title, 50, array('exact'=>false,'html'=>false,'ending'=>''));
                $this->Post->saveField('slug', Inflector::slug($post_title));

                // Redirect the user to the newly created post (pass the slug for performance)
                $this->redirect(array('controller'=>'posts','action'=>'view','id'=>Tiny::toTiny($this->Post->id),'slug'=>$this->Post->slug));
            }
            else
            {
                $this->Session->setFlash('Server broke!');
            }
        }

So what I need to do now is save the related Topic data which is typed in here in the view:

<?php echo $this->Form->create(); ?>

<?php echo $this->Form->input('Post.title'); ?>

<?php echo $this->Form->input('Post.content', array('type'=>'textarea','label'=>false)); ?>

<?php echo $this->Form->input('Topic.title', array('type'=>'textarea','label'=>'Topics')); ?>

<button type="submit" class="orangeButton small">Create</button>

<?php echo $this->Form->end(); ?>

I have looked at the CakePHP docs and it seems something like saveAll is what I need? But I'm confused as I'm not 100% sure how to use it also it's important to note that a user can save more than one topic to the database and the topics themselves are all unique so for example you can't create a topic that already exists it would instead just use the existing id for the linker.

Can anyone help? As I feel this is rather complex...

1

1 Answers

2
votes

You could do something like:


$this->Post->saveAll($this->data, array('validate'=>'first'));

The use of array('validate'=>'first'); ensures that both of our models are validated before saving. Did you mean something like that.

Hope it helps