如何使用 Slim Framework post 多个表单到同一路由?

how to post multiple forms to same route using SlimFramework?

我有以下视图 (main.php),其中包含两个单独的表单 post 到同一路线:

<form class="form" id="first_form" action="{{ urlFor('main.post') }}" method="post">
    // form data
</form>

<form class="form" id="second_form" action="{{ urlFor('main.post') }}" method="post">
    // form data
</form>

这是呈现该视图的路由逻辑以及 post 表单数据:

$app->get('/main', function() use ($app) {
    $app->render('main.php');
})->name('main');

$app->post('/main', function() use ($app) {
    // do something
})->name('main.post');

现在在我的 $app->post 方法中,我想区分提交的表单并相应地执行单独的逻辑,如下所示:

$app->post('/main', function() use ($app) {
    if(first form was submitted) {
       // do something
    } else if(second form was submitted){
       // do something else
    }
})->name('main.post');

我要实现的目标需要使用中间件吗?如果不是,我需要实现什么逻辑来完成这个看似简单的任务

您可以在表单中包含一个隐藏字段,指示提交了哪个表单。

<form class="form" id="first_form" action="{{ urlFor('main.post') }}" method="post">
    <input type="hidden" name="which" value="first_form">
    // form data
</form>

<form class="form" id="second_form" action="{{ urlFor('main.post') }}" method="post">
    <input type="hidden" name="which" value="second_form">
    // form data
</form>

然后在您的路线中检查 which 输入的值。

$app->post('/main', function() use ($app) {
    $which = $app->request()->post('which')
    if ('first_form' === $which) {
        // do something
    } else if ('second_form' === $which){
        // do something else
    }
})->name('main.post');