Basically I use jQuery to show/hide fields on the page. The controller will not know which radio option has been selected… do you mean I should send an ajax call to the controller to change the scenario?
Thanks for that. However the problem with that now is upon first page load those fields are not rendered as required, i.e. we don’t have “label class=required”. So the user wil not know that the field is required until after the form has been submitted and they are given the error.
You can have a 100 (or as many as you want) seniores all with different fields or variation of fields.
$model=new Vehicle('Car');
$mode->attributes = $_POST['car'];
$model->validate();
//you can check multiple scenarios by changing it and running the validate method
$mode->setScenario("ANOTHER_ scenario");
$mode->validate();
//though you could run into problems if you don't fully understand how these work
//you can also individually validate fields if need be
$model->validate("car_make");
//rules
public function rules()
{
return array(
array('car_make', 'required', 'on'=>'Car'),
array('boat_make', 'required', 'on'=>'Boat'),
array('can_fly', 'require', 'on' => "Car, Airplane, UFO"),
array('price', 'require', 'on' => "Car, UFO"),
);
}
The best way is probably to just use rules! You can target multiple fields by using the ON option;
e.g. the can_fly field will only be required if the scenario is Car, Airplane, UFO but the price will only be required if the scenario is CAR or UFO.
call var_dump($model->getScenario()) after $model->setScenario() this should print a different scenario name after each call, if its blank then something is wrong with your post request!
So in my form, $_POST[‘vehicle_type’] is “Car” and $_POST[‘journey_from’] is “Home”. This should mean that both ‘car_make’ and ‘return_datetime’ fields should be required. At the moment, only ‘return_datetime’ field is showing as an error.
Each time you call validate() it resets the previous error messages because they were for a different scenario! so you need to build an array of errors to use later.
so after each ->validate call you need to collect the errors by calling $model->getErrors() (adding them to new array $allErrors) and after the last validate set the errors again $mode->addErrors($allErrors)