dougang5993 2012-03-05 09:22
浏览 102
已采纳

从CakePHP视图中调用控制器的方法

I've been wondering what the best way to do this would be. I've got a SubmissionsController and within it, a view() method which is the display for each submission. All submissions have favorites, and users can vote on those favorites. I want to change an icon depending on whether or not the user voted on something previously. I've thought about doing it something like this:

// checkExistingFavorite would be a boolean method which returns true if the user has             already favorited it
<?= if (SubmissionsController::checkExistingFavorite($userId, $submissionId)) { ?>
<span style="favorited">Remove Favorite</span>
<? } else { ?>
<span style="not-favorited">Favorite</span>
<? } ?>

But obviously, I shouldn't be calling the SubmissionsController directly from within my view. My question is what's the best way to handle this? It'd need to be checked each time a user goes to view a submission though, so I'm not sure if I should even cache this?

  • 写回答

2条回答 默认 最新

  • doubeishuai6598 2012-03-05 09:30
    关注

    This should be done in the relevant controller method, otherwise you would be violating the MVC principles underpinning Cake. You could create a checkExistingFavorite($userId, $submissionId) function in your Submission model, so that it would be available to all controller actions.

    After checking for existing favorites using the function in the view() method of SubmissionsController (by calling $this->Submission->checkExistingFavorite()) you could set a variable for the view to true or false ($this->set('hasExistingFavourite', $boolean)).

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 itunes恢复数据最后一步发生错误
  • ¥15 关于#windows#的问题:2024年5月15日的win11更新后资源管理器没有地址栏了顶部的地址栏和文件搜索都消失了
  • ¥15 看一下OPENMV原理图有没有错误
  • ¥100 H5网页如何调用微信扫一扫功能?
  • ¥15 讲解电路图,付费求解
  • ¥15 有偿请教计算电磁学的问题涉及到空间中时域UTD和FDTD算法结合的
  • ¥15 vite打包后,页面出现h.createElement is not a function,但本地运行正常
  • ¥15 Java,消息推送配置
  • ¥15 Java计划序号重编制功能,此功能会对所有序号重新排序,排序后不改变前后置关系。
  • ¥15 关于哈夫曼树应用得到一些问题