Reputation: 187
So I'm still getting the hang of CakePHP, and I've been working on a site that includes multiple polls for people to vote on.
Basically I have a table called "entries" which are the subjects people vote on. Entries has a field called "vote_value" which is an integer that can store both positive and negative values. People vote on these entries, either + or - and the entry's vote value is then affected.
The problem: I'm not sure what the proper method of modifying the vote_value field would be. There's an up and down arrow that the people see on the index of entries, and I'd like that to refresh the page (or eventually just reload the vote_value without refresh) with that entry's new vote value.
I had thought about making a method that modifies the vote_value field in the model, but I believe that's hardcore breaking the point of MVC. Do I have to create another action in my controller just for this?
Any help is appreciated!
Upvotes: 0
Views: 42
Reputation: 4522
Yes, you need to create an action in your controller for this. You're probably gonna call it by ajax when casting votes, so the action would need to respond with a json or a true or false, you don't need to create a view for this. Something like
class EntryController extends AppController {
public function castVote($voteValue) {
//some logic or whatever
$this->Entry->changeValue($voteValue);
//don't create view
$this->autoRender = false;
echo 'all ok or some other message';
return;
}
}
$this->Entry->changeValue($voteValue)
is a function inside the Entry model, in case you need to use the logic for adding values (say, an user can just vote once, for example) somewhere else. That way, you reuse code. Or you can add all that logic in the controller, but I would advise against that, better to have fat models than fat controllers.
If you want the ajax in the view to update the new value, then instead of some random message, make the $this->Entry->changeValue($voteValue)
return the actual value, and echo that in the controller to the view
//inside controller
$newValue = $this->Entry->changeValue($voteValue);
$this->autoRender = false;
//check that the value is a number, not boolean, so you know the update was valid
echo $newValue;
return;
I've put the functions in the Entry model and controller, based on what you explained, but put the functions where you feels is more logic to have them.
Upvotes: 1