user1082754
user1082754

Reputation:

PHP Slim framework - multiple HTTP methods

I am trying to route multiple HTTP methods (GET and POST) to display the same content. For instance, I have a register page:

$app->map('/admin/register', function () use ($app) {
    $app->render('/admin/register.twig');
})->via('GET', 'POST');

This will display the register form upon GET and POST requests. I then want to specify 'extra stuff' to happen on POST.

$app->map('/admin/register', function () use ($app) {
    $app->render('/admin/register.twig');
})->via('GET', 'POST');

$app->post('/admin/register', function () use ($app) {
    // Validate register information
});

However, the second function is being ignored. I want to do this so that I can then display error messages above the register form. How would I go about achieving this?

Upvotes: 2

Views: 4108

Answers (2)

Martijn
Martijn

Reputation: 1390

If you don't want the post route to be ignored by Slim, you need to use the 'pass' helper in your generic map route, like so:

$app->map('/admin/register', function () use ($app) {
    if($app->request()->isPost()) {
       $app->pass();
    }
    $app->render('/admin/register.twig');
})->via('GET', 'POST');

$app->post('/admin/register', function () use ($app) {
    // Validate register information
});

Here's the documentation on it: http://www.slimframework.com/documentation/develop#routing-helpers-pass

Upvotes: 2

Iaroslav Vorozhko
Iaroslav Vorozhko

Reputation: 1719

You need to modify first function, add following code in it to detect post/get methods:

if ( $app->request()->isPost() ){
echo 'Post request';
}

Upvotes: 2

Related Questions