2
votes

I have a Competition model, that has many Entry models.

[edit] Schema looks (roughly) like this:

Competition:

id INT(11)

name VARCHAR(50)

date DATETIME

Entry:

id INT(11)

competition_id INT(11)

user_id INT(11)

answer VARCHAR(50)

isWinner INT(1)

In my pickWinner view, I have a form that loops through all related entries - offering the isWinner field to allow the user to pick an entry as the winner. Saving the related model etc is pretty standard and that all works fine.

I'm trying to validate the form so that at least one of the Entry models has isWinner set to true (the user has to pick at least one winner).

I obviously can't apply the validation rule to the Entry model - as each model only knows about itself and not the values of the other models.

Only one Entry model should be set as the winner - how do I add a validation rule to Competition, so that it can detect that one of its child Entry models has isWinner set to true?

1
so you are saying that the entries have already been created? and user will only be selecting an entry as the winner in this view? - bool.dev
Exactly so, yes. Thanks for putting it better than I did! - Hippyjim

1 Answers

0
votes

One way to achieve this would be to add a relation to the Competition model to detect if it has a winner, something like;

public function relations()
{
    return array(
        ...
        'winners' => array(self::STAT, 'Entry', 'competition_id', 'condition'=>'`t`.`isWinner` = true'),
        ...
    );
}

Then the following should return the number of winners for the given competition:

$competition = Competition::model()->findByPk($id);
$winners = $competition->winners;

Not tested, so you may need to alter a little.

EDIT

Ok, to get this info before you save you could do something like the following: if for example in your pickWinner view you have a field for each model and it's submitting back as an array, for example like $_POST[Entry][$model->id]['isWinner'] for each model, can you not simply cycle through those making sure one is set to true? e.g:

$winners = 0;
foreach(array_keys($_POST[Entry]) as $key)
{
    if($_POST[Entry][$key]['isWinner']=='true')
        $winners++;
}

if($winners==0)
{
    echo "You selected no winners.";
} else if($winners>1) {
    echo "You selected too many winners.";
} else if($winners==1) {
    echo "Woot, 1 winner!";
}

Again, this depends on how your pickWinner form is laid out.