Jared Garcia Jared Garcia - 4 years ago 108
PHP Question

how to post multiple forms to same route using SlimFramework?

I have the following view (main.php) that contains two separate forms that post to the same route:

<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>


Here is the route logic that renders that view and also post the form data:

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

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


Now within my
$app->post
method, I would like to differentiate between which form was submitted and do separate logic accordingly, like so:

$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');


Does what I am trying to accomplish need to utilize Middleware? if not, what logic do i need to implement to accomplish this seemingly simple task?

Answer Source

You could include an hidden field in your form which indicates which form was submitted.

<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>

Then in your route check the value of which input.

$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');
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download