简体   繁体   中英

Calling a controller's method from within the view 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?

you can check this condition in controller
based on this set one flag 0 OR 1, if multiple data then make array of the flag status
pass this array to view
base on passed array OR value you can set this condition
so we can achieve that business logic and representation logic is different

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) ).

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