Custom Yii Rule for Unique Attribute Validation

You’ve probably seen it or experienced at some point when registering for a site where you must pick a unique username or subdomain for account registration. However, this is can be tedious to implement in both frameworks and non-framework solutions. Luckily, Yii has validation rules that can be implemented easily and can be user-defined for special cases. Therefore, I’ve created this custom validation rule that checks for uniqueness of a row value for a given column within a model.

First, we need to add the rule to the array of rules

array("company_name, email", "doesNotExist")

Next, we need to define the method doesNotExist:

public function doesNotExist($attribute, $params){

	$count = self::model()->count("{$attribute}=:attribute", array(":attribute" => $this->getAttribute($attribute)));

	if($count > 0){
		$this->addError($attribute, "This ".strtolower($this->getAttributeLabel($attribute))." already exists please choose a different value.");
	}
}

Once implemented it will display an error within the form notifying the user that the value for the field they entered is not unique within the system.

Try Catch vs If…Which to use?

When it comes to error handling while coding there are several options available. We have if statements, try and catch, throw exceptions or even handle the it silently by logging or just letting it go. So to make it simple I’ve come down to this simple question:

Do you know the intended response and are you not expecting an error?

  • If you answered yes, then use an if statement. If you know the possible outcomes then you can handle the response of the system.
  • If you answered no, the place the statement in try/catch block. If you don’t know what could possibly happen then don’t try to handle the outcomes until you know what you are dealing with.
As an added piece of precaution, you can always wrap a code block with try/catch to handle any possible unknown situation that may go wrong, even if you are already handling it through other conditional statements.

AMPScript Language Module For TextWrangler

I’ve created a language module for TextWrangler/BBedit which has been made available for public download on Github. Currently, it will highlight all AMPScript functions and reserved words. Future upgrades look to add complete function Intellisense and function documentation. Download it here!

In case you don’t have TextWrangler you can download it here. And, for reference, check out AMPScript.