A
A
Alexey Verkhovtsev2019-04-14 14:18:17
symfony
Alexey Verkhovtsev, 2019-04-14 14:18:17

How to deserialize an array that comes from a Symfony 4 form?

There is a form class, I send it with Ajax and the data array looks like this
name_form[fields]: value
I want to deserialize it all into an object

if ($request->isXmlHttpRequest()) {
            $objectNormalizer = new ObjectNormalizer();
            $normalizers = [$objectNormalizer];
            $encoders = [new JsonEncoder()];
            $serializer = new Serializer($normalizers, $encoders);
            $data = $request->getContent();
            $result = $serializer->deserialize($data, SiteCreateDto::class, 'json');
            var_dump($result); exit;
        }

But the object is naturally not filled.
How to decide? Or what to read?
PS It is also necessary to ignore some fields from the form

Answer the question

In order to leave comments, you need to log in

1 answer(s)
B
BoShurik, 2019-04-15
@BoShurik

I don’t understand why you create a serializer so strangely?
Firstly, ObjectNormalizerit has a few more dependencies for its full-fledged work
. Secondly, it’s more correct to get it through DI.

public function submitAction(SerializerInterface $serializer, Request $request)
{
    if ($request->isXmlHttpRequest()) {
        $data = $request->getContent();
        $result = $serializer->deserialize($data, SiteCreateDto::class, 'json');
        var_dump($result); exit;
    }
}

If it didn’t help out of the box ObjectNormalizer, then you will need to write your own: https://symfony.com/doc/current/serializer/custom_...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question