Skip to content

[2.0][Shop] Error while hydrating resource in ResourceLivePropTrait if resource is not initialized #17911

@HugoDiag

Description

@HugoDiag

Sylius version(s) affected

2.0.6

Description

When emitting an event to refresh a live component (SummaryComponent and WidgetComponent for offcanvas), the first call isn't working beacause cart is null for each live component.
My component is used to add to cart, and then refresh every component displaying informations about it.

By doing this, I'm able do refresh the cart, with the Order I just created

$this->emit(FormComponent::SYLIUS_SHOP_CART_CHANGED, array("cartId" => $cartId));

But doing this result in an error because both live components have this prop :

#[LiveProp(hydrateWith: "hydrateResource", dehydrateWith: "dehydrateResource")]
public ?ResourceInterface $cart = null;

And the hydrateResource is like so :

public function hydrateResource(mixed $value): ?ResourceInterface
{
    return $this->repository->find($value);
}

As the cart is null in the live component, $value is null and it result in this exception : The identifier id is missing for a query of App\Entity\Order\Order

Even if the refreshCart is supposed to hydrate the cart from the id when given, the #[LiveProp] is called first

How to reproduce

When adding a product to cart, if the order is not yet created (so only on the first call, when live components are initalized with 'cart': null,
just emit the FormComponent::SYLIUS_SHOP_CHANGED with a cartId

$this->emit(FormComponent::SYLIUS_SHOP_CART_CHANGED, array("cartId" => $cartId));

Possible Solution

Testing if the value is null prevent Doctrine to throw an error, and allow refreshCart (or other method) to be called, to update the prop

public function hydrateResource(mixed $value): ?ResourceInterface
{
    if (null !== $value) {
        return $this->repository->find($value);
    }

     return null;
}

This would also allow Sylius to refresh live components when adding to cart instead of refreshing the whole page, by emitting the event instead of redirecting to an URL

Additional Context

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    Potential BugPotential bugs or bugfixes, that needs to be reproduced.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions