Using custom fields on a CActiveRecord which aren't on the DB table

Hi, I have a model with a date field, but in the form I collect the date through 3 separate dropdowns.

Is it possible to have some automation so I can build the date field from the 3 separate values in beforeSave() or beforeValidate() and if the validation fails, have the selected options be selected again on the form?


The algorithm is:

  1. Add 3 properties to the model.

  2. In beforeValidate() merge them or do what you need and put the result into the "date" property.

  3. Add a validation rule for the "date" property.

  4. In afterValidate() method you can check if there are any validation errors for this property (CModel.getError() method). If yes, then you can add 3 more errors for your separate fields (to highlight them in a form).

Ok, but how do I do keep the dropdown selections selected when reloading the form with the error messages?

If my dropdowns were table fields, they would get selected because of the ActiveRecord features.

Currently I do this manually:

echo CHtml::activeDropDownList( $userProfileModel, 'BirthDay', $days,

                	array( 'options'=> array ( 

                			$_POST['UserProfile']['BirthDay'] => 

                				array( 'selected' => true ) ) ) );

And also how do I get those custom attributes automatically populated from the form submission so I can use them to build the date in beforeValidate().

The attributes are named the same as the form fields.

Just add them as public properties in the model. I necessary, populate them in afterFind().


Oh sorry, they weren’t being populated because they weren’t declared as safe nor they had any rules.