How to set model rules/validation for dynamically generated fields from DB

Hi,

I have 2 tables namely X and Y.

Table X have a column named ‘Machine_Type’.

Table Y have a column named ‘Machine_Output_by_Type’.

For model Y ‘_form’, I have a sets of dynamically generated textfield based on the data(Machine_Type) fetched from table X.

The text field is generated using CHtml::textField.

I will need to validate all the fields to ensure that it only accept numbers.

All the dynamically generated fields stored in variable ‘$Dynamically_Gen_Fields’ are loaded to Model Y rules.





		// NOTE: you should only define rules for those attributes that

		// will receive user inputs.

		return array(

                       array($Dynamically_Gen_Fields, 'integerOnly'=>true,'message'=>'Please enter only numbers for {attribute}.'),


                );




After added the above rules, when i try to save a record, i will get an error prompted to me that my fields are not defined.

May I know how to add rules for dynamically generated fields from DB ?

Is $Dynamically_Gen_Fields a string with comma separated names of attributes?

I think it would be easier to add virtual attribute to model and store there the array of generated fields. Inside rules you can add custom method to validate this virtual attribute where you can iterate through all the array elements.

Yes, $Dynamically_Gen_Fields is a string type variable with comma separated values.

Correct me if i am wrong, what you are saying is declare an array to store all dynamically generated fields.

Based on the array, I will need to write a custom validation method to validate all the elements in the array.

Can Yii CNumberValidator use to validate these dynamically generated fields instead ?

I’m not sure if there is other way you can use rules() for that. As for the CNumberValidator you can use it separately.

$validator = new CNumberValidator;

$validator->validate($model, array(‘field’));