Reputation: 458
I've only been working with Slim for a short while. I'm still on version 2. So far everything has been going just fine, but I've hit a little snag. I have a page that displays content based on a GET variable at the end of the URL. The url looks like the following...
http://localhost/trailcache.com/checklist/21
The first line of the get route looks like this...
$app->get('/checklist/:Id', function($Id) use($app) {
It ends like this...
})->name('checklist');
That Id parameter controls what info I'm pulling into the page and everything has been going just fine, but now I've added a contact form and with it, some validation. I'm writing to the DB and rendering the new content okay. The problem arises when I try to send errors back to the page. Currently it looks like this...
$app->render('user/checklist.php', [
'Id' => $Id,
'errors' => $v->errors(),
'request' => $request
])->name('checklist');
This doesn't work. The page is blank. The url it returns is...
http://localhost/trailcache.com/checklist
The documentation for render shows...
$app->get('/books/:id', function ($id) use ($app) {
$app->render('myTemplate.php', array('id' => $id));
});
Wouldn't that work in the post route the same way? It has on all my other pages.
How can it get pass those errors along with the correct GET variable so that the correct content displays?
Upvotes: 0
Views: 1801
Reputation: 458
After a few days of struggling with this, I found a solution. I first discovered map() and changed the first line to...
$app->map('/checklist/:Id', function($Id) use($app) {
and the end to...
})->via('GET', 'POST')->name('checklist');
so now the route renders the same whether it's coming from post or get. I then pointed the form to this named route...
<form action="{{ urlFor('checklist', {Id: Id}) }}" class="form" method="post">
and moved all the post logic inside this route. Since there is no need to validate if the request wasn't a post I used...
if($app->request->isPost()) {
and put the validation code inside. Refreshing the page after making a form submission would resubmit the form so if validation passed I added...
return $app->response->redirect($app->urlFor('checklist', array(
'Id' => $Id
)));
All I had to do was pass the errors to the template and it seems to be working perfectly.
Upvotes: 0
Reputation: 433
This works for me just fine.
return $this->renderer->render('myTemplate.php', array('id' => $id));
Hope it works for you.
Upvotes: 1