How do you handle form submissions in Slim Framework?

How do you handle form submissions in Slim Framework?

To handle form submissions in Slim Framework, follow these steps:

Step 1: Set up a POST route

Create a route to handle the form submission using the post() method in Slim.

Example

<?php
use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request;
use Slim\Factory\AppFactory;

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

$app = AppFactory::create();

// Define a route to show the form
$app->get('/form', function (Request $request, Response $response) {
    $form = '<form method="POST" action="/submit">
                <input type="text" name="name" placeholder="Your Name">
                <button type="submit">Submit</button>
             </form>';
    $response->getBody()->write($form);
    return $response;
});

// Define a POST route to handle form submission
$app->post('/submit', function (Request $request, Response $response) {
    // Retrieve form data
    $data = $request->getParsedBody();
    $name = $data['name'] ?? 'Guest';

    // Return a response
    $response->getBody()->write("Hello, " . htmlspecialchars($name));
    return $response;
});

$app->run();
?>

Step 2: Access Form Data

When the form is submitted, Slim retrieves the form data via $request->getParsedBody(). This method returns an associative array of form inputs. Use it to process the data as needed.

Step 3: Run and Test

Start your Slim app and test the form submission.

Related Questions & Topics

Powered and designed by igetvapeaustore.com | © 2024 codestap.com.