Skip to content

Flash Message

Syone edited this page May 29, 2024 · 2 revisions

Overview

Flash message component is designed to display messages to the user with customizable options. It can be used to show alerts or notifications on a web page.

FlashMessage php component

First of all, we need to add the component Sy\Bootstrap\Component\FlashMessage in the web page:

$this->setVar('FLASH_MESSAGE', new \Sy\Bootstrap\Component\FlashMessage());

This component embeds a javascript function that can be called to show a new message.

flash() javascript function

Arguments

  • message: This can be either a string or a JSON object.

    • If it's a string, it represents the message you want to display.
    • If it's a JSON object, it should have the following structure:
      {
        "title": "Your title here",
        "body": "Your message body here"
      }
    • The title and body are both strings that represent the header and the content of the message, respectively.
  • color (optional): A string that specifies the color of the alert message. This should be a valid Bootstrap alert color value (e.g., primary, secondary, success, danger, warning, info, light, dark). Default value is success.

  • autohide (optional): A boolean value that determines whether the message should automatically disappear after a certain period or if it requires manual dismissal by the user. Default value is true.

    • true: The message will auto-hide.
    • false: The message will stay visible until the user dismisses it manually.

Usage Example

flash({ title: 'Success!', body: 'Your operation was completed.' }, 'info', false);

How to show a flash message after a redirection

Sometimes you may have to show a flash message right after a redirection. You have 2 ways to achieve this.

1. Javascript

Set a JSON on session storage called flash-message before performing a redirection in javascript. The JSON structure must follow the flash function arguments structure.

Example:

// 1. Save message on session storage
sessionStorage.setItem('flash-message', JSON.stringify({
	"message": {
		"title": "Success!",
		"body": "Your operation was completed."
	},
	"color": "info",
	"autohide": false
}));

// 2. Redirect to destination
window.location.href = 'https://example.com/redirect';

2. PHP

Set a message on server session before a php redirection. You can use the static helper function:

\Sy\Bootstrap\Lib\FlashMessage::setMessage(string|array $message, string $color = 'succes', boolean $autohide = true): void

Example:

// 1. Save message on session
\Sy\Bootstrap\Lib\FlashMessage::setMessage(
	['title' => 'Success!', 'body' => 'Your operation was completed.'],
	color: 'info',
	autohide: false
);

// 2. Redirect to destination
$this->redirect('https://example.com/redirect');

Clone this wiki locally