Skip to content

[Router] Can't put a default Enum value in a controller action #49203

Closed
@florentdestremau

Description

@florentdestremau

Symfony version(s) affected

6.2, possibly 6.1

Description

When defining routes with enums, the only way to make a default parameter work is by defining it in the #[Route] attribute. You can't define it in PHP:

#[Route('/nullable/{postEnum}')]
public function enumRouteNullable(?PostEnum $postEnum = null): Response
{
    // works without parameter, but no default value
    return $this->render('home/enumRoute.html.twig', ['enum' => $postEnum]);
}

#[Route('/default/{postEnum}')]
public function enumRouteDefault(PostEnum $postEnum = PostEnum::VLOG): Response
{
    // doesn't compile, `Symfony\Component\Routing\Route cannot contain objects.`
    return $this->render('home/enumRoute.html.twig', ['enum' => $postEnum]);
}

#[Route('/default/{postEnum}', defaults: ['postEnum' => PostEnum::VLOG->value])]
public function enumRouteDefaultString(PostEnum $postEnum): Response
{
    // works, with proper default value
    return $this->render('home/enumRoute.html.twig', ['enum' => $postEnum]);
}

The second solution is the most convenient one, but is not allowed, I get this error: Symfony\Component\Routing\Route cannot contain objects. (screenshot below)

How to reproduce

I made a test project that crashes accordingly. One controller with the use case, and another controller checking that it's valid with a pure string parameter.

https://github.com/florentdestremau/enum-router-bug

Possible Solution

It goes back to the fact that Backed Enum classes have no __toString() method and this makes the router compiling crash. There is some treatment for route generation that should detect enums and call the ->value method.

Additional Context

image

Metadata

Metadata

Assignees

No one assigned

    Labels

    FeatureGood first issueIdeal for your first contribution! (some Symfony experience may be required)Help wantedIssues and PRs which are looking for volunteers to complete them.Routing

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions