[solved] Validation rule to check if input value exists in array

I have field ‘town_id’ in my Enquiry model (FK to Town model)

In my front end form I display the town dropdown as follows:

Town model:




public function getTowns()

{

	return CHtml::listData($this->findAll(), 'id', 'name');

}



Enquiry Model:




public function getEnquiryTown()

{

	return Town::model()->Towns[$this->town_id];

}



Enquiry View:




<?php echo $form->dropDownList($model, 'town_id', Town::model()->Towns); ?>



This all works fine - the dropdownlist is populated with the listData from the getTowns() method.

However using developer toolbar in Firefox one can convert select element in to a free text field. Now if a user was to input an invalid value this would break the system when I call the getEnquiryTown() method above.

It will give an ‘undefined index’ error. So what is the best way to prevent such issues occurring? How to perform the validation to check if the input value exists in the array before saving the record?

You can define a custom validation rule in your model. See here