Search code examples
symfonysymfony4multi-tenant

How to generate right route in twig with dynamic sub-domain?


I have a multi-tenant APP based on sub-domain that's working properly but I have an issue with generated link in Twig templates.

All the generated link are on the default sub-domain and not the current one

routes.yaml

app_customer:  
  resource: '../src/Controller/Customer/'  
  host: "{subdomain}.domain.com"  
  defaults:  
    subdomain: tenant1  
  requirements:  
    subdomain: tenant1|tenant2  

SecurityController.php

class SecurityController extends AbstractController
{
    /**
     * @Route("/login", name="app_login", methods={"GET","POST"})
     */
    public function login(AuthenticationUtils $authenticationUtils)
    {
        // get the login error if there is one
        $error = $authenticationUtils->getLastAuthenticationError();
        // last username entered by the user
        $lastUsername = $authenticationUtils->getLastUsername();

        return $this->render('security/login.html.twig', [
            'last_username' => $lastUsername,
            'error'         => $error,
        ]);
    }
}

login.html.twig

<form action="{{ path('app_login') }}" method="post">...</form>

will always generate https://tenant1.domain.com/login however the current url is tenant2.domain.com


Solution

  • I believe it is always generating https://tenant1.domain.com/login because you have "tenant1" set as the default value for subdomain and you do not pass a different value when you call path()

    Try this :

    {% set currsubdomain = app.request.getHttpHost()|split('.')|first %}
    
    <form action="{{ path('app_login', {subdomain: currsubdomain }) }}" method="post">...</form>
    

    Or maybe just pass the whole host:

    <form action="{{ path('app_login', {host: app.request.getHttpHost}) }}" method="post">...</form>