0

I have two tables articles and tags and third association table articles_tagsnow i want to save data in articles_tags when create new article and user select multiple tags from drop down my controller code is below

public function add()
{
    $article = $this->Articles->newEntity();
    if ($this->request->is('post')) {
          $article = $this->Articles->patchEntity($article, $this->request->data, [
            'associated' => ['Tags']
          ]);

        if ($this->Articles->save($article)) {
            $this->Flash->success(__('The article has been saved.'));
            return $this->redirect(['action' => 'index']);
        } else {
            $this->Flash->error(__('The article could not be saved. Please, try again.'));
        }
    }

    $tags = $this->Articles->Tags->find('list',[
                                            'keyField' => 'id',
                                            'valueField' => 'name'
                                        ]);

    $this->set(compact('article','tags'));
    $this->set('_serialize', ['article','tags']);
}

and my view code is below

<?php 
    $this->Form->create($article);
    echo $this->Form->input('title');
    echo $this->Form->input('status');  
    echo $this->Form->select('tags.tag_id',
                                $tags,
                                ['empty' => '(choose one)', 'multiple' => true,]
                            );
    echo $this->Form->button(__('Submit'));
    echo $this->Form->end();
?>

and my article and tag model code is below

public function initialize(array $config)
{
    parent::initialize($config);

    $this->table('articles');
    $this->displayField('title');
    $this->primaryKey('id');

    $this->addBehavior('Timestamp');
    $this->belongsToMany('Tags', [
        'foreignKey' => 'article_id',
        'targetForeignKey' => 'tag_id',
        'joinTable' => 'articles_tags'
    ]);
}


public function initialize(array $config)
{
    parent::initialize($config);

    $this->table('tags');
    $this->displayField('name');
    $this->primaryKey('id');

    $this->addBehavior('Timestamp');

    $this->belongsToMany('Articles', [
        'foreignKey' => 'tag_id',
        'targetForeignKey' => 'article_id',
        'joinTable' => 'articles_tags'
    ]);
}

but when i saving data than data save only in articles table only related tag id and article id not saving in article_tags table don't know what is the problem please help me

Thanks

Deepak Goyal
  • 1,186
  • 2
  • 13
  • 26

1 Answers1

0

correct your view code

<?php 
$this->Form->create($article);
echo $this->Form->input('title');
echo $this->Form->input('status');  
echo $this->Form->select('tags._ids',
                            $tags,
                            ['empty' => '(choose one)', 'multiple' => true,]
                        );
echo $this->Form->button(__('Submit'));
echo $this->Form->end();

?>

Ruchi
  • 17
  • 6