That works but its not the right way (its partly there), imho the $_POST should not be used directly inside the model, you should have just made those fields part of the Enquiry array! so instead you could go;
if($this->vehicle_type=='Car' && empty($this->car_make))
It will make the code more reusable, what would happen if you manually wanted to test just once case? like wanted to make sure the car_make required during a different use case e.g. writing tests or a different situation you might not have thought of yet!
e.g. $mode->vehicle_type = ‘plane’; your solution will fail! you will start to understand more, once you get used to MVC but before you do that read more on how Models work dude!
One of your previous posts make me think (rightly or wrongly) you assume Yii has built-in solutions for all problems, don’t make that mistake! Yii is there to help you not to give you ready made solutions! rules only cover certain cases e…g require, range, boolean etc
Anyway it does look like that you came to some sort of conclusion as you created your own methods! it would have been similar to the afterValidate callback, remember its there to be used, why else would Yii have it?
Heres a simple solution which reduce the amount of code if you want to do more checks, this however does not cover other cases which you might want handling through rules) This could be improved allot but I don’t have the time…
This assumes vehicle_type and journey_from are part of the Enquiry array!
class Enquiry extends CActiveRecord
{
//.....
public function rules()
{
return array(
array('car_make, return_datetime, vehicle_type, journey_from', 'safe'),
array('car_make', 'validateDependOnAnotherField', 'dependOn' => 'vehicle_type',
'ifValue' => 'Car'),
array('return_datetime', 'validateDependOnAnotherField', 'dependOn' => 'journey_from',
'ifValue' => 'Home'),
);
}
public function validateDependOnAnotherField($attribute, $params)
{
if ((empty($this->$attribute) && $this->{$params['dependOn']} == $params['ifValue']))
{
$this->addError($attribute, $this->getAttributeLabel($attribute) . " - is required");
}
}
//....
}
ideally Yii should have a "if" option for rules, probably a expression or callback which returns true of false (but only applies the rule if returning true)
e.g.
array('car_make', 'require', 'if' => '$data->vehicle_type == "Car"'),
//or
array('car_make', 'require', 'if' => 'methodNameWhichDoesASimilarThing'),
I’m only offering advice here, my suggestions aren’t the only solution/s, other people will have different/better solutions than me, thats just the way programming works! So what you have to manually add error messages, why did Yii provide you a method to do that? never to be used?
To me you did overcomplicate it dude!!! then why have you just simplified it by not using scenarios, huh?
Anyway I’ll get back to you again if need be!