3

How do I do PUT and DELETE form submissions in Slim 4? I have the following route:

$group->get('/sites/create', SitesController::class . ':create')->setName('sites_create');
$group->get('/sites/{id}/edit', SitesController::class . ':edit')->setName('sites_edit');
$group->post('/sites', SitesController::class . ':createSubmit')->setName('sites_create_submit');
$group->put('/sites', SitesController::class . ':editSubmit')->setName('sites_edit_submit');

Here is my :

<form action="/sites" method="POST">
    <label for="name">Site name</label>
    <input type="text" class="form-control" id="name" name="name">                 
    <input type="hidden" name="_METHOD" value="PUT">
    <button type="submit">Submit</button>
</form>

This is how I would have done it in Slim 3.

But it isn't going to the editSubmit method, instead it's going to the createSubmit method.

How do I submit using these methods?

Nima
  • 3,309
  • 6
  • 27
  • 44
Martyn
  • 6,031
  • 12
  • 55
  • 121

1 Answers1

3

According to Slim 4 documentation, you still can override the form method using _METHOD parameter in a POST request body, or by using X-Http-Method-Override header.

The important point (from docs) is that you need to add Slim\Middleware\MethodOverrideMiddleware to your app to be able to override form method.

Here is a fully working example:

<?php

require __DIR__ . '/../vendor/autoload.php';

use Slim\Factory\AppFactory;

$app = AppFactory::create();
$app->addRoutingMiddleware();
$app->add(new Slim\Middleware\MethodOverrideMiddleware);

$app->get('/', function($request, $response){

    $form =<<<form
    <form action="/put" method="post">
        <input type="hidden" name="_METHOD" value="PUT"/>
        <button type="submit">Send PUT request</button>
    </form>
    <form action="/delete" method="post">
        <input type="hidden" name="_METHOD" value="DELETE"/>
        <button type="submit">Send DELETE request</button>
    </form>
form;

    $response->getBody()->write($form);
    return $response;
});

$app->put('/put', function($request, $response){
  $response->getBody()->write('The request method is: ' . $request->getMethod());
  return $response;
});
$app->delete('/delete', function($request, $response){
    $response->getBody()->write('The request method is: ' . $request->getMethod());
    return $response;
});

$app->run();
Nima
  • 3,309
  • 6
  • 27
  • 44
  • Thanks. I could have sworn I read something about having to implement this in Slim 4 but couldn't find it when I needed it. Working now. I don't suppose you'd take a look at my other Slim 4 issue with $response in middleware - https://stackoverflow.com/questions/60176905/slim-4-middleware-redirect-on-the-way-in - double your points :) – Martyn Feb 12 '20 at 08:14
  • Glad I could help. I did see your other question and I think it is a duplicate. Please refer to the comment on the question. – Nima Feb 12 '20 at 09:13