简体   繁体   中英

CakePHP: creating my own functions

I have an Article controller & model. I want to have a function that adds one to an integer when a link is clicked. So I have say a "i like" button (link) it takes me to Articles/thumbsup it will then take the thumbsup field of that article and increment it by one, then save the article, and redirect to the view.

I'm not sure how to modify records in this way. I need to load the article, modify the data and then save it.

My hope is that this be handled by javascript so noone will see the url change.

Can someone help me out here?

Thanks,

Jonesy

Thanks,

Billy

You can do that with an AjaxRequest.

models/article.php:

function thumbsup($id = null)
  {
  $conditions = array('Article.id' => $id);
  $this->updateAll(
    array('Article.thumbsup' => 'Article.thumbsup + 1'),
    $conditions
    );
  $article = $this->find(
    'first',
    array('conditions' => $conditions, 'fields' => array('Article.thumbsup'))
    );
  return $article['Article']['thumbsup'];
  }

controllers/articles_controller.php:

function thumbsup($id = null)
  {
  $this->set('count', $this->Article->thumbsup($id));
  $this->layout = 'ajax';
  }

views/articles/thumbsup.ctp:

<?php echo $count; ?>

webroot/js/thumbsup.js:

$(document).ready(function()
  {
  $('.iLikeSomething').click(function()
    {
    $.post('http://yoursite.com/articles/incrementThumbsup/'+this.id, function(data)
      {
      $('#iLikeSomethingCount').html(data);
      });
    });
  });

Html sample for clicking:

<span class="iLikeSomething" id="insertYourArticleIdHere" style="cursor: pointer;">iLike</span>
<div id="iLikeSomethingCount">0</div>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM