I am using Alto router for a project. My problem comes when I submit a form, I can't find a solution to make redirection works. My project structure:
root
|/elements
|- layout.php
|/public
|- index.php
|/templates
|- add.php
|- home.php
|- login.php
I tried diffents url in the action attributes. I also tried to leave it blank and use header("Location") to redirect.
Here's how I handle the router:
$router = new AltoRouter();
$router->map('GET', '/', 'home', 'home');
$router->map('GET', '/login', 'login', 'login');
$router->map('GET', '/add', 'add', 'add');
$match = $router->match();
if (is_array($match)) {
if (is_callable($match['target'])) {
call_user_func_array($match['target'], $match['params']);
} else {
$params = $match['params'];
ob_start();
require "../templates/{$match['target']}.php";
$pageContent = ob_get_clean();
}
require '../elements/layout.php';
} else {
echo '404';
}
Now the on the add page I have a form that should add to my db and then redirect to home page. This is where I'm stuck (also, the db part for inserting might contain errors but i'll work on it later):
<?php
use App\App;
if (!empty($_POST)) {
$he = App::getPDO()->prepare("INSERT INTO huiles(name_simple, name_science, elements, dilution, props) VALUES (?, ?, ?, ?, ?)");
$params = [
$_POST['name_simple'],
$_POST['name_science'],
$_POST['elements'],
$_POST['dilution'],
$_POST['props']
];
$he->execute($params);
}
?>
<form action="<?= $router->generate("home") ?>" method="post">
<div class="form-group">
<label for="name_simple">Nom</label>
<input type="text" name="name_simple" class="form-control">
</div>
<div class="form-group">
<label for="name_simple">Nom scientifique</label>
<input type="text" name="name_science" class="form-control">
</div>
<div class="form-group">
<label for="name_simple">Elements</label>
<input type="text" name="elements" class="form-control">
</div>
<div class="form-group">
<label for="name_simple">Dilution</label>
<input type="text" name="dilution" class="form-control">
</div>
<div class="form-group">
<label for="name_simple">Propriétés</label>
<input type="text" name="props" class="form-control">
</div>
<button class="btn btn-primary">Ajouter</button>
</form>
How should I handle the router to redirect to home page after the submit (and also after the data is added to the db) ?
You must first define your route to your processing file with the POST method because you are sending a form :
In your view :
In treatement.php