Search code examples
dynamicroutessilex

Create route at user convenience


I need to create a small application with a homepage where the user can fill a form with a unique field. The field will be used as the name of a room, and the user redirected to this page. Every other user who enter the same room name will be redirected to the same page, and will be able to chat with users in this room.

My problem is that I can't find a way with silex 2 to make this work.

I created the homepage, and it seems to work. I have a form and can enter the name of the room:

$app->match(
'/',
function (Request $request) use ($app) {
    $data = array(
        'room' => 'Name of the room',
    );

    $form = $app['form.factory']->createBuilder(FormType::class, $data)
        ->add('room', TextType::class)
        ->getForm();

    $form->handleRequest($request);

    if ($form->isValid()) {
        $data = $form->getData();
        $roomName = $data['room'];

        //return $app->redirect('/room/' . $roomName);
        $subRequest = Request::create($app['url_generator']->generate('/room/' . $roomName), 'GET');

        return $app->handle($subRequest, \Symfony\Component\HttpKernel\HttpKernelInterface::SUB_REQUEST, false);
    }

    return $app['twig']->render('base.twig', array('form' => $form->createView()));
}
)->bind('home');

As you can see, I tried with redirect, and with a subrequest. But both cases don't work, as I receive a 404.

The code which is suppose to catch the room is:

$app->match(
'/room/{name}',
function ($name) use ($app) {
    return $app['twig']->render('room.twig', array('name' => $name));
}
)->bind('room');

Does anyone have an idea on how I could make this work?

Thank you for reading. Any help will be appreciated.


Solution

  • I finally found the solution.

    I had to add a .htaccess file in my web folder. The important part of this file was this, for anyone having the same problem:

    <IfModule mod_rewrite.c>
        Options -MultiViews
        RewriteEngine On
        RewriteCond %{REQUEST_FILENAME} !-f
        RewriteCond %{REQUEST_FILENAME} !-d
        RewriteRule ^ index.php [L]
    </IfModule>