Note that there are some explanatory texts on larger screens.

plurals
  1. POModel validation Symfony2
    primarykey
    data
    text
    <p>I have read how to validate forms in server side with sf2. The solution is by using the Constraints in the Entity as annotations, validation.yml or inside the EntityType (Form).</p> <p>Everything is fine, however, all of these validations work just with the form. But when you instance a new object and try to persist, validation doesn't work.</p> <p>I will give you an example. </p> <p>Imagine I have a user entity:</p> <pre><code>/** * @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-&gt;addPropertyConstraint('username', new \Symfony\Component\Validator\Constraints\NotBlank()); $metadata-&gt;addPropertyConstraint('email', new \Symfony\Component\Validator\Constraints\NotNull()); } } </code></pre> <p>Then, in some controller I try to save my form with:</p> <pre><code>$this-&gt;form = $this-&gt;create(new UserType()); $this-&gt;form-&gt;setData(new User()); $this-&gt;form-&gt;bind($this-&gt;request); if( $this-&gt;form-&gt;isValid()) { //Persist with entity manager } </code></pre> <p>Everything works perfectly because I have an association between my Entity and my form. But what happen if i need to instance an object without a form?. I should do something like this:</p> <pre><code>$user = new User(); $user-&gt;setUsername("username"); //Persist with entity manager </code></pre> <p>If I do that, entity is not validated and DB throws an error because the field "email" is required.</p> <p>Should I always associate my entity with the form to validate? If that is the case, I don't agree at all because if I am working with web services, I don't wanna create a form just to validate on the server side.</p> <p>So, how could I do this validation?. Thanks for your help.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload