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?
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 yourSubmissionmodel, so that it would be available to all controller actions.After checking for existing favorites using the function in the
view()method ofSubmissionsController(by calling$this->Submission->checkExistingFavorite()) you could set a variable for the view totrueorfalse($this->set('hasExistingFavourite', $boolean)).