php - Use custom normalizer to modify class properties


I have an entity with 2 properties,name andphoto. Thename property is read from the database but I have to fill thephoto property with some other information.

I have followed the Writing a Custom Nomalizer tutorial from the docs and I have made my custom normalizer:


namespace App\Serializer;

use App\Entity\Style;
use Symfony\Component\Serializer\Normalizer\DenormalizerInterface;
use Symfony\Component\Serializer\Normalizer\NormalizerInterface;
use Vich\UploaderBundle\Templating\Helper\UploaderHelper;

final class StyleNormalizer implements NormalizerInterface, DenormalizerInterface
    private $normalizer;

    private $uploaderHelper;

    public function __construct(NormalizerInterface $normalizer, UploaderHelper $uploaderHelper)
        if (!$normalizer instanceof DenormalizerInterface) {
            throw new \InvalidArgumentException('The normalizer must implement the DenormalizerInterface');

        $this->normalizer = $normalizer;
        $this->uploaderHelper = $uploaderHelper;

    public function denormalize($data, $class, $format = null, array $context = [])
        return $this->normalizer->denormalize($data, $class, $format, $context);

    public function supportsDenormalization($data, $type, $format = null)
        return $this->normalizer->supportsDenormalization($data, $type, $format);

    public function normalize($object, $format = null, array $context = [])
        if ($object instanceof Style) {

        return $this->normalizer->normalize($object, $format, $context);

    public function supportsNormalization($data, $format = null)
        return $this->normalizer->supportsNormalization($data, $format);

But thephoto property is not filled with the required information.

After a little bit of debug I have found that thesupportsNormalization method is executed two times (for each database element). If I print the$datavariable, I got the entityname property the first time and thephoto property withnull value the second time. I never got the entireStyle entity. Then thesupportsNormalitzation method always returnsfalse.

How can I get the fullStyle entity and modify its properties?





Try to add this to yoursupportsNormalization methods :

public function supportsNormalization($data, $format = null)
        $this->normalizer->supportsNormalization($data, $format)
        && is_object($data) && $data instanceof Style::class

People are also looking for solutions to the problem: preg replace - PHP preg_replace [LINK]mylink[/LINK]


Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.