Skip to content

[Serializer] Groups annotation/attribute on class #18657

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Aug 1, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 32 additions & 2 deletions serializer.rst
Original file line number Diff line number Diff line change
Expand Up @@ -295,7 +295,7 @@ Using Serialization Groups Attributes
-------------------------------------

You can add :ref:`#[Groups] attributes <component-serializer-attributes-groups-attributes>`
to your class::
to your class properties::

// src/Entity/Product.php
namespace App\Entity;
Expand All @@ -321,7 +321,37 @@ to your class::
private string $description;
}

You can now choose which groups to use when serializing::
You can also use the ``#[Groups]`` attribute on class level::

#[ORM\Entity]
#[Groups(['show_product'])]
class Product
{
#[ORM\Id]
#[ORM\GeneratedValue]
#[ORM\Column(type: 'integer')]
#[Groups(['list_product'])]
private int $id;

#[ORM\Column(type: 'string', length: 255)]
#[Groups(['list_product'])]
private string $name;

#[ORM\Column(type: 'text')]
private string $description;
}

In this example, the ``id`` and the ``name`` properties belong to the
``show_product`` and ``list_product`` groups. The ``description`` property
only belongs to the ``show_product`` group.

.. versionadded:: 6.4

The support of the ``#[Groups]`` attribute on class level was
introduced in Symfony 6.4.

Now that your groups are defined, you can choose which groups to use when
serializing::

use Symfony\Component\Serializer\Context\Normalizer\ObjectNormalizerContextBuilder;

Expand Down