course when you register on learnphalcon
The examples on this site are currently tested to work on Phalcon V3.4 and Phalcon Devtools V3.2 Some issues may arise when using later versions.

Please get in touch or post a comment below the post if you encounter a problem.

Having already explained how to populate a dropdown list with information coming from the persistence layer it may seem like overkill to add a validation rule to ensure values entered in that attribute must be contained in a set of values stored elsewhere in the database. For many systems this may well be the case but building proper validation into the domain layer adds strength and flexibility to the system which may aid it survive into the future.

As systems grow and evolve they may well look to change their reason for being. The front end could change radically or they could start taking input from a remote source. In this instance the simple dropdown list will be circumvented. Adding a validation rule to the model to build the rule into the model is relatively straightforward. The following example illustrates this.

Here we need to use the InclusionIn Validator. Edit /app/models/member and add the following use statements to the top of the model class.

use Phalcon\Validation as Validation;
use Phalcon\Validation\Validator\InclusionIn as InclusionInValidator;

Then add the following function at the bottom.

public function validation()
   $validator= new Validation();
   $memberTypes = Membershiptype::find()->toArray();  
   foreach($memberTypes as $item) { //this converts from an array of assoc arrays to a simple array
	   $types[] = $item['membershiptype'];
   $iValidator = new InclusionInValidator(["message" => "Please choose from the list of valid member types",
					"domain"  => $types]);
   $validator->add('membertype', $iValidator);
   return $this->validate($validator);

Given the Membershiptype table which you added in Step 1 - this validation function will ensure that no Member can be added with a Membership type which is not already present in the list of available membershipTypes.