core icon indicating copy to clipboard operation
core copied to clipboard

UniqueEntity not fully working on PUT

Open GHuygen opened this issue 2 years ago • 9 comments

API Platform version(s) affected: 3.2.18

Description
If you have a unique property in your entity it is impossible to update other properties with PUT

How to reproduce
Example entity:

#[ORM\Entity]
#[ORM\UniqueConstraint(columns: ['name'])]
#[UniqueEntity(fields: ['name'], errorPath: 'name', ignoreNull: false)]
#[ApiResource(
    normalizationContext: ['groups' => ['client_channel:read']],
    denormalizationContext: ['groups' => ['client_channel:write']],
    order: ['name' => 'ASC'],
)]
#[ApiFilter(filterClass: SearchFilter::class, properties: ['name' => 'ipartial'])]
#[ApiFilter(filterClass: OrderFilter::class, properties: ['name'])]
class ClientChannel
{
    #[ORM\Id]
    #[ORM\GeneratedValue]
    #[ORM\Column]
    #[Groups(groups: ['client_channel:read'])]
    private ?int $id = null;

    #[ORM\Column(length: 255)]
    #[Groups(groups: ['client_channel:read', 'client_channel:write'])]
    #[Assert\Length(max: 255)]
    #[Assert\NotBlank]
    public string $name = '';
    
    #[ORM\Column(length: 255)]
    #[Groups(groups: ['client_channel:read', 'client_channel:write'])]
    #[Assert\Length(max: 255)]
    public string $description = '';
}

It is impossible to update the description of this created entity as it consistently returns the following response:

{
    "@id": "/validation_errors/23bd9dbf-6b9b-41cd-a99e-4844bcf3077f",
    "@type": "ConstraintViolationList",
    "status": 422,
    "violations": [
        {
            "propertyPath": "name",
            "message": "This value is already used.",
            "code": "23bd9dbf-6b9b-41cd-a99e-4844bcf3077f"
        }
    ],
    "detail": "name: This value is already used.",
    "hydra:title": "An error occurred",
    "hydra:description": "name: This value is already used.",
    "type": "/validation_errors/23bd9dbf-6b9b-41cd-a99e-4844bcf3077f",
    "title": "An error occurred"
}

Additional Context
It seems that the entity, which is being updated, is not fully loaded during validation. In the UniqueEntityValidator, there is this code to exclude its own

        if (!$result || (1 === \count($result) && current($result) === $entity)) {
            return;
        }

but $entity is not holding the id of the entity that needs updating.

Edit: image In the screenshot, it can be seen that I'm attempting to update the entity with an ID of "1". Interestingly, the cause of failure is reported to be the same entity with an ID of "1".

If I'm not using the intended way, please let me know the correct method.

GHuygen avatar Apr 03 '24 13:04 GHuygen

add entityClass

#[UniqueEntity(fields: ['name'], errorPath: 'name', ignoreNull: false, entityClass: self::class)]

SakhriHoussem avatar Apr 08 '24 11:04 SakhriHoussem

@SakhriHoussem The issue still persists despite implementing this solution.

if i use :

#[ApiResource(
    operations: [
        new Put(extraProperties: ['standard_put' => false]),
    ],
)]

Everything works as expected, but I'm unsure if this is a smart idea. Thoughts?

GHuygen avatar Apr 29 '24 08:04 GHuygen

Has anyone else experienced this issue?

I would expect this to be a basic function. It seems comparable to updating a user's name when there's a unique constraint on the email address.

Am I doing something wrong?

GHuygen avatar May 21 '24 06:05 GHuygen

I have same problem. It seems that the entity does not check the current value before updating

PS I figured it out, it turns out I had records in the database with the same unique field value.

bogdankorobka avatar May 28 '24 17:05 bogdankorobka

I'm having the same problem. I experienced, that it works fine using PATCH. When using PUT, the ID is not set properly either and therefor, the symfony validation thinks it's a POST request, creating a new entity, instead of updating the existing one.

I guess, the only right solution now is using PATCH instead of PUT.

sfarkas1988 avatar Jun 19 '24 10:06 sfarkas1988

From docs:

Note: Current PUT implementation behaves more or less like the PATCH method. Existing properties not included in the payload are not removed, their current values are preserved. To remove an existing property, its value must be explicitly set to null. Implementing the standard PUT behavior is on the roadmap, follow issue #4344 to track the progress.

For now by default PUT is PUT, PATCH is PATCH.

d0niek avatar Jun 30 '24 20:06 d0niek

For people experiencing this, if you are using jsonLd try adding the @id filed in the request (even though it seems redundant as you already sending this info in the URL). Versus things are not working if it's not provided explicitly.

ili101 avatar Jul 16 '24 08:07 ili101

I have the same problem, the PUT operation doesn't run with the normalizationContext configuration. It changes values to base calculated as a modification date.

mahdi6464 avatar Jul 29 '24 14:07 mahdi6464

The object validated on PUT is the entity fetched from the database and populated with your payload, not a fresh instance, so UniqueEntity sees the same row it is comparing against.

Both workarounds reported in this thread, extraProperties: ['standard_put' => false] and switching to PATCH, point at the interaction between the standard PUT semantics and how the constraint compares entities, rather than at a defect in the constraint integration itself. We could not build a case where an already fetched entity is wrongly rejected.

Closing as not planned. If you have a reproduction on 4.4 where the validated object really is the fetched entity, please open a new issue with it.

soyuka avatar Sep 25 '26 12:09 soyuka