symfony4fosjsroutingbundle

fosjsrouting dumping incorrect paths


My normal Symfony 4 routes work as expected; but the urls generated by FOSJsRouting are missing the webroot/public prefix that automatically appears in a Twig-generated url.

Twig call and output

{{path(ci_chemical_show,{id:11409}) // http://localhost:8087/CIRdev/public/chemical/show/11409

FOSJsRouting call and output

Routing.generate(ci_chemical_show,{id:11409}) //http://localhost:8087/chemical/show/11409

My setup

My symfony config/routes/annotations.yaml file (which works) looks like this:

controllers:
  resource: '../../src/Controller/'
  type: annotation

The controller annotation looks like this:

/**
 * Class ChemicalController
 * @package App\Controller\Chemical
 * @Route("/chemical")
 *
 */
class ChemicalController extends AbstractController
{
    /**
     * @Route("/show/{id}", name="ci_chemical_show", requirements={"id"="\d+"}, options={"expose"=true})
     * @param Request $request
     * @param Chemical $chemical
     * @return Response
     */
    public function show(Request $request, Chemical $chemical) {
        return $this->render(':chemical/Chemical:show.html.twig', ['chemical' => $chemical]);
    }

My config/routes/for_js_routing.yaml file is the default:

fos_js_routing:
    resource: "@FOSJsRoutingBundle/Resources/config/routing/routing-sf4.xml"

I've installed and configured FOSJsRouting as described in the Symfony 4 docs.

I ran fos:js-routing:dump --format=json --target=public/js/fos_js_routes.json which produced the following json, which I think is wrong since it has nothing about CIRdev/public in it:

{
 "base_url": "",
 "routes": {
    "ci_chemical_show": {
     "tokens": [
        [
         "variable",
         "\/",
         "\\d+",
         "id",
         true
        ],
        [
         "text",
         "\/chemical\/show"
        ]
     ],
     "defaults": [],
     "requirements": {
        "id": "\\d+"
     },
     "hosttokens": [],
     "methods": [],
     "schemes": []
    },
//etc.

Since this is a very vanilla Symfony 4 setup, I'm at a loss as to why FOSJsRouting is behaving this way. Thoughts?


Solution

  • FOS JS Routing (and console commands in general) know nothing about the application being installed on a subdirectory since they don't have access to the RequestContext necessary to compute it so it's assuming that the app is installed in the DocumentRoot.

    The parameter base_url in your generated routes are a dead giveaway that it is possible to configure, but you have to do it manually. You can read about this caveat in the Commands section of the FOS-Js.

    Set the parameter request_context_base_url in the bundle configuration, but doing this is not necessary when you load your routes via the controller instead of dumping. You can see all config options by running bin/console config:dump-reference.