This forum has moved to a new location and is in read-only mode. Please visit talk.octobercms.com to access the new location.

shina
shina

How do I use Flash::success('hello world') on frontend like we use on backend?

On backend we use

\Flash::success('foobar');

Then it automatic reflects on backend form/list.

How to replicate this behavior on frontend?

axomat
axomat

Flash:: works in the front end as well, you just need to add something like the following to your partial.

{% flash %}
    <div class="alert alert-{{ type == 'error' ? 'danger' : type }}">
        {{ message }}
        <button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>
    </div>
{% endflash %}

Last updated

shina
shina

However, this approach works only when the page is refreshed.

On backend, the alert is displayed automatically just after the request was made.

axomat
axomat

Maybe the flash plugin is more useful to you. I have not used it but it might be worth trying.

shina
shina

Yes, I was considering to use this plugin. However it adds unecessary overhead with bootstrap notify, since we already have all the resource on october, we only need to reuse it some way.

Well, thanks for your help anyway. I will leave my solution here if I have any hehe.

Gregbee
Gregbee

hi, i think you want to use flash message with ajax handler ?

firt you need to setup a partial for flash messages october flash message and wrap it in a div with what ever id you want (need to be unique) put that partial inside a page or a layout.

then in your component onHandler function : ajax flash message

public function onWhatever(){
    /* do your logic and set flashMessages*/
    \Flash::success('flash from ajax handler');
    return ['#my_flash_message_id' => $this->renderPartial('my_flash_message_partial')];
}

your flash message appears without reload

Last updated

Asinox
Asinox

I was looking for this, let me try it!

Thank you!

lbrowning11071
lbrowning11071

I having some difficulties getting my head around this. My flash messages appear but only on page reload.

I've tried using a partial but that just leaves extra HTML in my layout and does not get populated with the message.

in... public function onSignin()

        Flash::error('bummer');
        return ['#my_flash_message_id' => $this->renderPartial('my_flash_message_partial')];

in... my_flash_message_partial.htm

{{ message }}

in... my test page html

[flashmessage]

<?php

function onSignin() {

    try {
        return $this->account->onSignin();
    }
    catch (Exception $ex) {
    //  Log::error($ex);
    //  Flash::error($ex);
        Flash::error('Login error');
    }

}

Perhaps I'm missing something fundamental in nature... if anyone could provide a link to a guide or tutorial on how to implement flash messages that appear immediately on ajax error - such as incorrect password, I would be super grateful.

Also attempting to use [flashmessage]

I've tried a few combinations of with and without Flash being called on the page versus using the component Ajax handler itself.

Sorry if this seems somewhat disjointed.... but I guess the essence of it is I don't understand why the event doesn't fire and subsequently calls the message alert after page refresh.

lbrowning11071
lbrowning11071

some of my markup seems to have disappeared but hopefully it's enough to go on.

lbrowning11071
lbrowning11071

Problem solved... what I didn't mention (and probably should have) is that I was trying to make this work with the rainlab user component. It was throwing an exception on Auth::authenticate which prevented my flash message from executing. Here is a solution for handling that in user/components/Account.php

https://octobercms.com/forum/post/error-handling-and-flash-a-potential-solution

Igor Jacaúna
Igor Jacaúna

I found this solution: Used on my theme/partial/page:

{% flash %}
        <script>
            // only execute once the DOM is loaded
            document.addEventListener("DOMContentLoaded", function () {
                $.oc.flashMsg({text: '{{ message }}', 'class': '{{ type }}', 'interval': 10})
            }, false);
        </script>
   {% endflash %}

Created a JS file and included in my theme:

+function ($) { "use strict";

var FlashMessage = function (options, el) {
    var
        options = $.extend({}, FlashMessage.DEFAULTS, options),
        $element = $(el)

    $('body > p.flash-message').remove()

    if ($element.length == 0)
        $element = $('<p/>').addClass(options.class).html(options.text)

    $element.addClass('flash-message fade')
    $element.attr('data-control', null)
    $element.append('<button type="button" class="close" aria-hidden="true">×</button>')
    $element.on('click', 'button', remove)
    $element.on('click', remove)

    $(document.body).append($element)

    setTimeout(function(){
        $element.addClass('in')
    }, 1)

    var timer = window.setTimeout(remove, options.interval*1000)

    function removeElement() {
        $element.remove()
    }

    function remove() {
        window.clearInterval(timer)

        $element.removeClass('in')
        $.support.transition && $element.hasClass('fade') ?
            $element
                .one($.support.transition.end, removeElement)
                .emulateTransitionEnd(500) :
            removeElement()
    }
}

FlashMessage.DEFAULTS = {
    class: 'success',
    text: 'Default text',
    interval: 2
}

// FLASH MESSAGE PLUGIN DEFINITION
// ============================

if ($.oc === undefined)
    $.oc = {}

$.oc.flashMsg = FlashMessage
}(window.jQuery);

And use this CSS in my theme:

.flash-message {
position: fixed;
width: 500px;
left: 50%;
top: 13px;
margin-left: -250px;
color: #ffffff;
font-size: 13px;
padding: 10px 30px 10px 15px;
z-index: 10000;
-webkit-border-radius: 2px;
-moz-border-radius: 2px;
border-radius: 2px
 }

.flash-message.fade {
    opacity: 0;
    filter: alpha(opacity=0);
    -webkit-transition: all 0.5s,width 0s;
    transition: all 0.5s,width 0s;
    -webkit-transform: scale(0.9);
    -ms-transform: scale(0.9);
    transform: scale(0.9)
 }

    .flash-message.fade.in {
        opacity: 1;
        filter: alpha(opacity=100);
        -webkit-transform: scale(1);
        -ms-transform: scale(1);
        transform: scale(1)
     }

.flash-message.success {background: #8da85e}

.flash-message.error {background: #cc3300}

.flash-message.warning {background: #f0ad4e}

.flash-message.info {background: #5fb6f5}

.flash-message button {
    float: none;
    position: absolute;
    right: 10px;
    top: 8px;
    color: white
 }

    .flash-message button:hover {color: white}

.flash-message.static {
    position: static !important;
    width: auto !important;
    display: block !important;
    margin-left: 0 !important
 }

And works!

Last updated

ImadCH
ImadCH

@Gregbee, Thank you very much, compact solution.

hambern
hambern

I use the @Gregbee's sollution and it shows the message perfectly upon submiting. But when I reload the page, it still shows. So it shows the flash message twice. Anyone else got this?

dai.mike16723
dai.mike16723

here is my solution, hopes it help.

<form  data-request-flash data-request-validate>
mobile:<input type="text" name="mobile" value="xxxx">
<button data-request-flash data-attach-loading data-request='onSendMobileVerifyCode'>
    Send
</button>
<hr>
verifycode :<input type="text" name="verify" value="">
<hr>
<button data-request-flash data-attach-loading data-request="onMobileBinding">
    Verify
</button>
</form>

here is my component function

public function onSendMobileVerifyCode()
{
....
        \Flash::success('verify code has been send');
}
LMBdev
LMBdev

This solution is the most straightforward and simple to implement... espcially if you are trying to replace the ugly JavaScript dialog boxes when logging in with RainLab.User Account:

dai.mike16723 said:

here is my solution, hopes it help.

<form  data-request-flash data-request-validate>
mobile:<input type="text" name="mobile" value="xxxx">
<button data-request-flash data-attach-loading data-request='onSendMobileVerifyCode'>
   Send
</button>
<hr>
verifycode :<input type="text" name="verify" value="">
<hr>
<button data-request-flash data-attach-loading data-request="onMobileBinding">
   Verify
</button>
</form>

here is my component function

public function onSendMobileVerifyCode()
{
....
       \Flash::success('verify code has been send');
}

Note that this does not address the error messages themselves, which can still be confusing.

roulendz
roulendz

hambern said:

I use the @Gregbee's sollution and it shows the message perfectly upon submiting. But when I reload the page, it still shows. So it shows the flash message twice. Anyone else got this?

Yes, on page reload Flash message persists Even if I change pages, Flash message shows up on next page! @Gregbee Do you have some solution?

auzadventure
auzadventure

dai.mike16723 said:

here is my solution, hopes it help.

<form  data-request-flash data-request-validate>
mobile:<input type="text" name="mobile" value="xxxx">
<button data-request-flash data-attach-loading data-request='onSendMobileVerifyCode'>
   Send
</button>
<hr>
verifycode :<input type="text" name="verify" value="">
<hr>
<button data-request-flash data-attach-loading data-request="onMobileBinding">
   Verify
</button>
</form>

here is my component function

public function onSendMobileVerifyCode()
{
....
       \Flash::success('verify code has been send');
}

Note

You only need to input the data-request-flash in the <form> tag, the button tag is not needed. This will trigger the flash to show.

Last updated

paulgrafx
paulgrafx

FIXED: it was to add 'data-request-flash' to the form tag.

I have done the following for this which works fine, apart from the issue if you refresh the page or redirect to another page with a flash message the error message stays on until you refresh a second time.

  1. Created a partial in my theme with the following called 'my_flash_message_partial'.
{% flash %}
    <div class="alert alert-{{ type == 'error' ? 'danger' : type }}">
    {{ message }}
    </div>
{% endflash %}
  1. Then on the login form it has the following.
<div id="my_flash_message_id">
    {% partial 'my_flash_message_partial' %}
</div>
  1. Then on the page.
[RainLab\User\Components\Account Account]

[account]
paramCode = "code"
redirect = "user/dashboard"
==
<?php
function onSignin()
{
    try {
        return $this->account->onSignin();
    }
    catch (Exception $ex) {
        Log::error($ex);
        Flash::error('Login details are not correct');
        return ['#my_flash_message_id' => $this->renderPartial('my_flash_message_partial')];
    }
}
?>
==

Do I need to reset the flash message on function onSignin()?

Last updated

netsmertia
netsmertia

You need to add the data-request-flash in your form tag

<form data-request="onSubmitForm" data-request-flash>
        // your form fields
        <button type="submit" class="btn btn-primary float-right">Next</button>
</form>

and in handler code use Flash::success('yes done') or Flash::error('your error') or throw a ValidationException

public function onSubmitForm() {
  if (!Auth::user) {
     Flash::error('please login');
  }
  Flash::success('product added');
}

or

public function onSubmitForm() {
       $validation = Validator::make(...);
       if ($validation->fails()) {
            throw new  ValidationException($validation);
       }
    }

https://octobercms.com/docs/ajax/extras#usage-example

1-19 of 19

You cannot edit posts or make replies: the forum has moved to talk.octobercms.com.