symfony - Model validation Symfony2 -


i have read how validate forms in server side sf2. solution using constraints in entity annotations, validation.yml or inside entitytype (form).

everything fine, however, of these validations work form. when instance new object , try persist, validation doesn't work.

i give example.

imagine have user entity:

/**  * @orm\entity  * @orm\table(name="sf_user")  */ class user{     /**      * @orm\id      * @orm\column(type="integer")      * @orm\generatedvalue(strategy="auto")      */     protected $id;      /**      * @var string      * @orm\column( name="username", type="string", length=50, unique=true )      */     protected $username;      /**      * @var string      * @orm\column( name="email", type="string", length=100, unique=true )      */     protected $email;      public static function loadvalidatormetadata(\symfony\component\validator\mapping\classmetadata $metadata)     {         $metadata->addpropertyconstraint('username', new \symfony\component\validator\constraints\notblank());          $metadata->addpropertyconstraint('email', new \symfony\component\validator\constraints\notnull());     }  } 

then, in controller try save form with:

$this->form = $this->create(new usertype()); $this->form->setdata(new user()); $this->form->bind($this->request);  if( $this->form->isvalid()) {     //persist entity manager } 

everything works because have association between entity , form. happen if need instance object without form?. should this:

$user = new user(); $user->setusername("username"); //persist entity manager 

if that, entity not validated , db throws error because field "email" required.

should associate entity form validate? if case, don't agree @ because if working web services, don't wanna create form validate on server side.

so, how validation?. help.

you can use validation service

$validator = $this->get('validator'); $validator->validate($user); 

see the docs this.


by way there cleaner way specify validation in entity.

use symfony\component\validator\constraints assert;  class user{  /**  * @assert\notnull  */ protected $username;  /**  * @assert\notblank  * @assert\email  */ protected $email; 

Comments

Popular posts from this blog

linux - Does gcc have any options to add version info in ELF binary file? -

android - send complex objects as post php java -

charts - What graph/dashboard product is facebook using in Dashboard: PUE & WUE -