Symfony 4 / Sonata: Using a primary key with a /

As strange as it may seem, I had to use an entity with a primary key set on a varchar field, and some values contained a " / ".

Until you are faced with the problem, it's impossible to imagine that it will cause an issue. And then, the drama unfolds.

image
An exception has been thrown during the rendering of a template ("Parameter "id" for route "admin_app_wtype_edit" must match "[^/]++" ("MACHIN/CHOSE" given) to generate a corresponding URL.").

In short, the slash is interpreted by the URL generator as a URL separator, which crashes the system.
Therefore, you need to modify the URL generator so that it turns this " / " into something else (essentially URL encoded), and then on the input, you need to modify the retrieved primary key value to select the object so that it performs the reverse transformation.

In your XxxAdmin.php file, add the following interface:

use Symfony\Component\Routing\Generator\UrlGeneratorInterface as RoutingUrlGeneratorInterface;

Then add the following two functions:

 public function generateUrl($name, array $parameters = [], $absolute = RoutingUrlGeneratorInterface::ABSOLUTE_PATH)
    {
       
        if(!empty($parameters['id'])){
            $parameters['id'] = str_replace("/","%2F",$parameters['id']);
        }
        
        return $this->routeGenerator->generateUrl($this, $name, $parameters, $absolute);
    }
    
    public function getObject($id)
    {
        $id=str_replace("%2F","/",$id);

        $object = $this->getModelManager()->find($this->getClass(), $id);
        foreach ($this->getExtensions() as $extension) {
            $extension->alterObject($this, $object);
        }
    
        return $object;
    }