Bummer! This is just a preview. You need to be signed in with a Basic account to view the entire video.
As a little bonus, let’s add some nice messages in the session flashes to give feedback to the user.
Styles for New Function display_success()
Name of bag: success
Name of class: alert-success
$messages = $session->getFlashBag()->get('success'); $response = '<div class="alert alert-success alert-dismissable">';
Success and Failure Flash Messages
- Adding Book
- Editing Book
- Logging In
- Logging Out
Display Flash Messages on Pages
Up until now when there's been an error,
we just redirect the user back to a form or page that they were just on.
But we do not provide any information.
I think we should fix this and show some sort of message.
When a message is only visible for
a single request, this is called a flash message.
The Symfony HttpFoundation package that we've been using
gives us a nice set of features to do this.
We'll be using Sessions for this, and attaching a message to its flashBag,
the storage area for all these messages.
The messages that are stored here are automatically deleted
when you retrieve them to display on the site.
The first thing we need to do
is open our Bootstrap file and
begin a session for our application.
This will create a new session object and start it.
This is essentially the same thing as doing session_start.
That gives us a lot more features to work with.
To show how this works, let's take a look at our login system.
Open the do login procedure and let's add some items to our session.
If a user's email is not found, we should let them know that the username was not
found when we send them back to the login page.
We need to add a line to this check for the empty username.
From the session object in the Bootstrap file, we get the FlashBag and
can add to it.
The first item is the key we want to use, in this case, error.
And the second is the message, Username was not found.
Internally, it will create an error array
with all the messages that belong to that key.
To display the message, we need to check for anything in the error FlashBag.
I think this calls for a nice helper function.
We'll call this display_errors.
And first we'll need to get the global session variable.
we check to see
if the FlashBag
has an error.
If not, we can return.
we need to get
Now we can create an alert with all the error messages.
Let's loop over
And finally, return the response.
Now we need to display errors on our login page.
Let's take a look at this in the browser.
If any errors exist, they will now show here.
We can expand this to show success messages and other kinds of messages.
Why don't you give it a shot and add the function to display success and
add these messages where you find appropriate?
Check the notes associated with this video for style examples.
You need to sign up for Treehouse in order to download course files.Sign up