On Thu, Jan 24, 2013 at 9:14 PM, Advantage+ <movepixels@gmail.com> wrote:
> I need to create a simple poll for users and stumped on saving the results
> when user submits the poll.
>
> Poll hasMany Question
>
> Poll hasMany Result
>
> Question hasMany Choice
This is how I did it:
Poll
hasMany PollQuestion
PollOption
belongsTo PollQuestion
hasMany PollVote
PollVote
belongsTo PollOption
The only model that needs to be directly associated with Poll is
PollQuestion. The others chain together.
> Pretty simple, but how do you save the results since viewing the poll
> creates a form to save Poll?
>
>
> View the poll/$id pulls all the questions and choices for each, but how /
> where to save the results?
>
> What would be the correct table for this? poll_results? results?
>
Save the result in poll_votes. I made my PollsController handle
everything. In the vote() action:
$this->Poll->PollQuestion->PollOption->PollVote->save()
The table only requires id, poll_option_id, and user_id columns, but
should include created as well.
In Poll::afterFind(), loop through the various questions, then each of
its options, summing the number of votes for each. Add a new 'total'
key in the data array with the results.
foreach($data as $k => $d)
{
if ( isset($d['PollOption']) && isset($d['PollOption'][0]['PollVote']) )
{
$data[$k][$this->alias]['total'] = 0;
/* sum individual and grand total of votes
*/
foreach($d['PollOption'] as $j => $option)
{
$total = sizeof($option['PollVote']);
$data[$k]['PollOption'][$j]['total'] = $total;
$data[$k][$this->alias]['total'] += $total;
}
/* get percentage only if not multiple select
*/
foreach($data[$k]['PollOption'] as $j => $option)
{
$per_cent = $option['total'] > 0
? floor( ( $option['total'] * 100 ) / $data[$k][$this->alias]['total'])
: 0;
$data[$k]['PollOption'][$j]['per_cent'] = $per_cent;
}
}
}
The "multiple select" thing is because some questions nneded to be
multiple choice. And therein was the cause of much grief, as I recall.
--
Like Us on FaceBook https://www.facebook.com/CakePHP
Find us on Twitter http://twitter.com/CakePHP
---
You received this message because you are subscribed to the Google Groups "CakePHP" group.
To unsubscribe from this group and stop receiving emails from it, send an email to cake-php+unsubscribe@googlegroups.com.
To post to this group, send email to cake-php@googlegroups.com.
Visit this group at http://groups.google.com/group/cake-php?hl=en.
Friday, January 25, 2013
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment