From c0e226a36a3ae0666c1cb41cc1eeb49c11c7a1c2 Mon Sep 17 00:00:00 2001 From: Anis Benna Date: Wed, 24 Mar 2021 14:20:58 +0100 Subject: [PATCH] Update custom_normalizer.rst Added a live example from an app using a custom normalizer. More details: https://stackoverflow.com/q/66781361/10543130 --- serializer/custom_normalizer.rst | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/serializer/custom_normalizer.rst b/serializer/custom_normalizer.rst index 2a0a60244ed..672e64d44d0 100644 --- a/serializer/custom_normalizer.rst +++ b/serializer/custom_normalizer.rst @@ -54,6 +54,26 @@ to customize the normalized data. To do that, leverage the ``ObjectNormalizer``: } } +If you're creating a REST api with a custom response, here's an example +of what you would have in the `normalize` function: + + public function normalize($product, string $format = null, array $context = []) + { + $data = $this->normalizer->normalize($product, $format, $context); + + // Here, add, edit, or delete your fields: + $data = [ + 'id' => $product->getId(), + 'name' => $product->getName(), + 'description' => $product->getDescription(), + 'price' => $product->getPrice(), + 'available' => $product->getAvailable(), + 'category' => $product->getCategory()->getName(), + ]; + return $data; + } + + Registering it in your Application ----------------------------------