Search code examples
symfonyjms-serializer

Symfony - How to deserialize with default values?


I'm starting to learn Symfony 4.

I want to deserialize datas from json data. (I'm using JMSSerializer)

This is my context : I have a Customer entity in src/App/Entity

class Customer {
    /**
     * 
     * @ORM\Id
     * @ORM\Column(type="integer")
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;
    /**
     * @ORM\Column(type="string", length=250)
     * @Assert\NotBlank()     
     */
    private $name;
     /**
     * @ORM\Column(type="string", length=250)
     * @Assert\NotNull
     */
    private $comment;

    public function __construct() {
    $this->comment = "";
    }
}

I have a CustomerController controller in src/App/Controller

class CustomerController extends Controller
{
    /**
     * @Route("/customers", name="customer_create")
     * @Method({"POST"})
     */
    public function createAction(Request $request)
    {
        $data = $request->getContent();
        //Il faudrait valider les données avant de les mettre en base de données
        $customer = $this->get('jms_serializer')->deserialize($data, 'App\Entity\Customer', 'json');        

        $em = $this->getDoctrine()->getManager();
        $em->persist($customer);
        $em->flush();

        return new Response('', Response::HTTP_CREATED);
    }
}

I post a request for creating a customer with the following JSON data:

{"name":"Customer Lambda"}

but I have the following error

NotNullConstraintViolationException

An exception occurred while executing 'INSERT INTO customers (id, name, comment) VALUES (?, ?, ?, ?)' with params [Resource id #99, "Customer Lambda", null]:

SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'comment' cannot be null

Is it possible to set a default value (empty string) for the comment field after deserialize? I was thinking that setting it in the Customer constructor will fix the issue but it is not the case.


Solution

  • 1º Why are you trying to set empty string if you have defined comment as not nullable.

    This:

     /**
     * @ORM\Column(type="string", length=250)
     * @Assert\NotNull
     */
    private $comment = "";
    
    public function __construct() {
    }
    

    Instead this:

     /**
     * @ORM\Column(type="string", length=250)
     * @Assert\NotNull
     */
    private $comment;
    
    public function __construct() {
    $this->comment = "";
    }