Enbici Entity
Enbici Entity is the module used in the Enbici framework in order to validate forms, and doctrine models.
How does it work?
Enbici entity currently only works with doctrine models by adding some simple validation options to the model class. Since the model are subclasses of EnbiciEntity then the validation will be applied each time you try to persist changes to the database.
Some examples
Lets continue using our user class but let us add some validation to it.
//in models/user.php
class User extends EnbiciEntity{
protected $name;
protected $email;
//Validation being added
public $validates_email_format_of = array("email");
public function getName(){
return $this->nombre;
}
public function setName($name){
$this->name = $name
}
public function getEmail(){
return $this->email;
}
public function setEmail($email){
$this->email = $email;
}
}
Now in order to make this validation work we need to tell doctrine that we need to validate models when they are about to be persisted in our yml mapping.
//in db/User.yml
User:
type: entity
id:
id:
type: integer
generator:
strategy: AUTO
fields:
name:
type: string
email:
type: string
lifecycleCallbacks:
prePersist: [validate]
And that's it! Now our models will be validated each time we try to store them in the database. The validation will throw an exception each time it fails so now we need to catch it.
//in application/controllers/UserController.php
public function createAction(){
$user = new User;
$postvars = $this->filter($_POST);
$user->name = $postvars["name"];
$user->email = $postvars["email"];
try{
$user->save();
} catch (ValidationException $e){
$this->flash($e->getMessages());
}
}
Validations
With that we can use the several validation methods available in EnbiciEntity.
Currently there are length validators, format validators, numerical validators, and presence validators.
//in models/user.php
class User extends EnbiciEntity{
protected $name;
protected $email;
//Validation being added
//you can set your own messages to it
public $validates_email_format_of = array("email" => array("msg" => "Email provided was not valid."));
public $validates_numericality_of = array("id");
//regular expression matching
public $validates_format_of = array("email" => ""/^.*(?=.{8,})/"");
//or
public $validates_format_of = array("email" => array(""/^.*(?=.{8,})/"", "msg" => "Email format was simply wrong."));
public $validates_length_of = array("email" => array("min" => 10, "max" => 255));
//...
}
Enbici Entity is still a work in progress but as you can see it provides easy access to validation methods and later you will be able to add your own validations, and also validate forms that don't depend on a doctrine model. Every validation method can take their own message so you can provide users with better explanations on why their information failed to be stored.
blog comments powered by Disqus