[size="5"]Summary
[/size]
In the standard implementation (e.g. using the CRUD generator) the search values in a grid are not validated. This means, if you e.g. enter ‘foo’ for an integer the SQL statement will bounce.
Therefore, it makes sense to validate also the search values. However, due to the prefixed operator (e.g. <> 10) the standard validation cannot be used.
With the following behaviour one can achive such a validation.
[size="5"]Behavior
[/size]
<?php
class EnsureValidSearchValuesBehavior extends CBehavior {
/**
* Performs the validation for search by cloning the object, stripping away the ops and then calling the standard validate one the clone
*
* @return boolean whether the validation is successful without any error.
* @see validate
*/
public function validateForSearch() {
$copy = clone $this->getOwner();
foreach ($this->getOwner()->getSafeAttributeNames() as $attrib) {
$value = $this->getOwner()->{$attrib};
if (is_array($value)) {
$copy->{$attrib} = NULL; // it is impossible to check the individual values
} else {
$value = "$value"; // enforce a string object
if (preg_match('/^(?:\s*(<>|<=|>=|<|>|=))?(.*)$/', $value, $matches)) {
$copy->{$attrib} = $matches[2];
}
}
}
$valid = $copy->validate();
// Append the errors found to the original model
$this->getOwner()->addErrors($copy->errors);
return $valid;
}
/**
* Checks via validateForSearch if the search values are proper; if not raises a HTTP 400 exception
*
* @see validateForSearch
*/
public function ensureValidSearchValues() {
if (!$this->getOwner()->validateForSearch()) {
throw new CHttpException(400, "At least one search parameter is not valid. Mindestens einer der Suchparameter ist nicht korrekt");
}
}
}
?>
[size="5"]Usage
[/size]
The usage is within the model class
[size="4"]Add the behavior to the function behaviors()
[/size]
public function behaviors(){
return array(
'EnsureValidSearchValuesBehavior' => array(
'class' => 'EnsureValidSearchValuesBehavior',
),
);
}
[size="4"]Extend the search function to ensure the validity
[/size]
public function search()
{
// Check for valid search values (using the EnsureValidSearchValuesBehavior)
$this->ensureValidSearchValues();
.........
}