8000 [Serializer] Add docs for attributes context key · symfony/symfony-docs@5d75696 · GitHub
[go: up one dir, main page]

Skip to content

Commit 5d75696

Browse files
authored
[Serializer] Add docs for attributes context key
1 parent 7c1f1c2 commit 5d75696

File tree

1 file changed

+40
-0
lines changed

1 file changed

+40
-0
lines changed

components/serializer.rst

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -333,6 +333,46 @@ You are now able to serialize only attributes in the groups you want::
333333

334334
.. _ignoring-attributes-when-serializing:
335335

336+
Selecting Specific Attributes
337+
-----------------------------
338+
339+
It is also possible to serialize only a set of specific attributes::
340+
341+
use Symfony\Component\Serializer\Serializer;
342+
use Symfony\Component\Serializer\Normalizer\ObjectNormalizer;
343+
344+
class User
345+
{
346+
public $familyName;
347+
public $givenName;
348+
public $company;
349+
}
350+
351+
class Company
352+
{
353+
public $name;
354+
public $address;
355+
}
356+
357+
$company = new Company();
358+
$company->name = 'Les-Tilleuls.coop';
359+
$company->address = 'Lille, France';
360+
361+
$user = new User();
362+
$user->familyName = 'Dunglas';
363+
$user->givenName = 'Kévin';
364+
$user->company = $company;
365+
366+
$serializer = new Serializer(array(new ObjectNormalizer()));
367+
368+
$data = $serializer->normalize($user, null, array('attributes' => array('familyName', 'company' => ['name'])));
369+
// $data = array('familyName' => 'Dunglas', 'company' => ['name' => 'Les-Tilleuls.coop']);
370+
371+
Only attributes that are not ignored (see below) are available.
372+
If some serialization groups are set, only attributes allowed by those groups can be used.
373+
374+
As for groups, attributes can be applied during both the serialization and deserialization.
375+
336376
Ignoring Attributes
337377
-------------------
338378

0 commit comments

Comments
 (0)
0