title: Datatransformer and json validation in symfony2 form
body: <p>I'm building a Rest API and I receive a json_encoded string from the clients. 
  I want this string to be decoded before saving my entity, because it's going into a <code>jsonb</code> field in PostgreSQL.</p>
  
  <p>The behavior I want is :</p>
  
  <ol>
  <li>Validate that the string is valid json, if not, add a violation in the form via a custom validator</li>
  <li>Automatically decode the string and set the json object in the entity property</li>
  </ol>
  
  <p>I've tried two different strategies</p>
  
  <ol>
  <li>In the entity <code>setMetadata($value) method</code>, if <code>$value</code> is a <code>string</code>, I decode it</li>
  <li>I created a DataTransformer that <code>json_decode</code> the value received in the form</li>
  </ol>
  
  <p>But both these solutions don't work because the custom validator I created is called after, and it calls directly <code>$lesson-&gt;getMetadata()</code>. Since the value has already been decoded (either in the <code>setMetadata() method</code> or in the <code>DataTransformer</code>, the <code>validator</code> receive either a <code>json object</code> or <code>null</code>. So I can't add a violation to the form, since I have no way to know if the value received was actually null, or if the string was malformed.</p>
  
  <p>Here is the lesson entity:</p>
  
  <pre><code>class Lesson extends BaseContent
  {
      […]
  
      /**
       * @var jsonb
       *
       * @ORM\Column(name="metadata", type="jsonb", nullable=true)
       * @KreactiveAssert\Json
       */
      private $metadata;
      […]
  }
  </code></pre>
  
  <p>Here is the custom validator:</p>
  
  <pre><code>class JsonValidator extends ConstraintValidator
  {
      public function validate($value, Constraint $constraint)
      {
          if ($value &amp;&amp; !json_decode($value)) {
              $this-&gt;context-&gt;addViolation($constraint-&gt;message, array('%string%' =&gt; $value));
          }
      }
  }
  </code></pre>
  
  <p>And here is the DataTransformer:</p>
  
  <pre><code>class StringToJsonTransformer implements DataTransformerInterface
  {
      /**
       * Transform a json object to a string
       * @param  Json|null $json
       * @return String
       */
      public function transform($json)
      {
          if (null === $json) {
              return "";
          }
  
          return json_encode($json);
      }
  
      /**
       * Transform a string to a json object
       * @param  String $string
       * @return Object
       */
      public function reverseTransform($string)
      {
          if (!$string) {
              return null;
          }
  
          throw new TransformationFailedException('error transforming');
  
          return json_decode($string);
      }
  }
  </code></pre>
  
  <p>Is there any way I can validate the input data in the form, and then set the metadata as a json object?</p>