Flight checking values for Propel

I’m using Propel ORM (v 1.6.4) for a new development and came across a limitation with validators. I’d hoped to use Propel validation rule messages to inform my users of bad input, but for some data types you need to provide correctly formatted input first time:

$starting_date = sanitise($_GET[‘starting_date’]);
// user mistyped date: ’03/08/20q2′
//Fatal Propel Exception here!

If you can’t set your date field, you can’t validate it. In turn this means you need your own form validation ahead of your Propel functionality.

The following sample ( a new function in my ‘Event’ class) goes some way to solving this. It allows you to pre-validate form entry using a Propel custom validator you specify and will return a Propel failure message as set in your schema validation rules.

Here’s the usage:…

if ($_GET[‘starting_date’] ):
$event = new Event();
$sanitisedFormVal = sanitise($_GET[‘starting_date’]);
if ($check = $event->flightCheckFail(‘StartingDate’,’DateValidator’,$sanitisedFormVal)) {echo $check;}
else { $event->setStartingDate($sanitisedFormVal);}

and here’s the Event class:class Event extends BaseEvent {
public function flightCheckFail($name,$validatorClass,$value) {
$colname = $this->getPeer()->getTableMap()->getColumnByPhpName($name)->getName();
$validators = $this->getPeer()->getTableMap()->getColumn($colname)>getValidators();
foreach($validators as $validatorMap) {
if ($validatorMap->getClass()==$validatorClass) {
$validator = BasePeer::getValidator($validatorMap>getClass());
if ( $validator->isValid($validatorMap, $value) === false) {
$failureMessage =  $validatorMap->getMessage();
if($failureMessage) {return $failureMessage;}
else {return false;}
} // Event

The function flightCheckFail rifles through the Propel object’s generated Peer and Map classes and injects the value you would set into a validation request.

If it fails, you get the Propel rule failure message back, which you can return to your user.

If the value passes validation, flightCheckFail returns false and you’re safe to setXXX the value in your Propel object.

You can read about the original problem as it presented itself on Stack Overflow.

Download the Gist here: https://gist.github.com/4673875