【问题标题】:CakePHP 3 - Deleting associated data using ajaxCakePHP 3 - 使用 ajax 删除关联数据
【发布时间】:2015-11-11 20:28:07
【问题描述】:

帖子可以有多个作者。

我想添加使用 Ajax 删除帖子中作者的可能性。

PostsAuthorsTable.php

$this->belongsTo('Users', [
    'className' => 'Users',
    'foreignKey'    => 'user_id',
    'joinType' => 'INNER'
]);

PostsTable.php

$this->hasMany('PostsAuthors', [ 'foreignKey' => 'post_id' ]);

PostsController.php

public function delete_author($authorID)
{
    $id = $_GET['authorID'];
    $this->Posts->PostsAuthors->delete($id);
    $this->autoRender = false;
}

查看:帖子 > edit.ctp(JavaScript 部分)

<?php $this->start('script'); ?>
<script>
    $(document).ready(function () { 
        $('.delete-author').on('click', function () {
            $.ajax({
                url: '<?= $this->Url->build(["action" => "delete_author"]) ?>',
                type: 'GET',
                data: { authorID: $(this).data('id') }
            });

            return false;
        });
    });
</script>
<?php $this->end(); ?>

查看:帖子 > edit.ctp(HTML 部分)

<?php foreach ($post_authors as $post_author): ?>
<tr>
    <td><?= $post_author->user->name ?></td>
    <td class="text-center">
        <a href="#" class="delete-author text-danger" data-id="<?= $post_author->id ?>">
            <i class="icon-trash"></i>
        </a>
    </td>
</tr>
<?php endforeach; ?>

感谢您的帮助。 :)

【问题讨论】:

  • 嘿,你为什么不用 Cake\View\Helper\FormHelper::postLink

标签: javascript php ajax cakephp cakephp-3.0


【解决方案1】:

我找到了解决办法。

PostsController.php

public function delete_author($authorID)
{
    $id = $_GET['authorID'];
    $entity = $this->Posts->PostsAuthors->get($id);
    $this->Posts->PostsAuthors->delete($entity);
    $this->autoRender = false;
}

【讨论】:

  • 分页表中可能更现代的 AJAX“删除”版本显示为 here 通过 Ajax plugin
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-02-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-12-07
相关资源
最近更新 更多