Is there any js function that will display these notifications that appear on top of the screen? Flash messages use these notifications, but I don't want to use flash messages, I want to display notification without refreshing a page.
1 Answer
Craft's JS/UI framework "Garnish" is largely undocumented, but exploring the Craft
object it exposes in the console, I found a few methods that might be useful:
// Good for confirmations (blue banners):
Craft.cp.displayNotice('Your changes have been saved.');
// Good for errors (red banners):
Craft.cp.displayError('Uh oh, something bad happened!');
// Custom flash names (for anything else—requires custom CSS):
Craft.cp.displayNotification('custom-flash-key', 'Something very special happened!');
The last one, displayNotification
is the abstract method, called by the first two. custom-flash-key
gets added to the notification as a classname.
-
-
-
@AugustineCalvino Generally speaking, flashes set from the back-end (i.e. a controller) should go through
Craft::$app->getSession()->setNotice($message)
and->setError($message)
. Craft will automatically render those notifications for you when the page loads! Commented Jan 19, 2023 at 17:52 -
@tenshi This still applies to Craft 4. 4.2.0 introduced rich notifications, which means these JavaScript methods now support additional arguments—haven't had a chance to document this, yet, though! Commented Jan 19, 2023 at 20:19