2

I'm building a plugin and want to trigger some JavaScript on an event being fired (eg an entry being saved). What is the best way to achieve this? Coming up short looking through the documentation and Stack Overflow.

  • What is it you're trying to achieve using Javascript? Where are you saving the entry? Is this trigger for the back end/front end? – Luke Pearce Aug 8 '16 at 12:24
  • thanks for reply @LukePearce - trying to clear localStorage on an entry save but needs to be tied to specific/defined sections (hence focus on using a plugin). This is for the back-end/control panel – Cole Henley Aug 8 '16 at 12:28
4

When an entry is saved, an Entry saved. flash message is set and displayed by Craft. You could use the Control Panel JS plugin to write a script to detect this flash message and perform your desired action.

The flash message is set in a div with an id="notifications". When there is no notification present, this div is empty. When there is a notification present, the div contains another div like this:

<div id="notifications">
    <div class="notification notice" style="opacity: 0; display: none;">Entry saved.</div>
</div>

If you test for the presence of this inner div and also the specific notification content (i.e. Entry saved.) you should be able to trigger the actions you need to.

| improve this answer | |
2

Since you're building your own plugin, you can make use of the UserSessionService's addJsFlash() method to queue up some JavaScript that will be injected and executed upon the next request after an entry is saved:

(In your plugin's main class)

public function init()
{
    craft()->on('entries.saveEntry', function (Event $event) {
      craft()->userSession->addJsFlash('(function () {
        if (window.Craft) {
            Craft.setLocalStorage("elementindex.Entry", "");
        }
      })();');
    });
}
| improve this answer | |
2

Thanks both for answers - realised that was probably going about things the wrong way so have tried a different approach. Using a plugin to store a timestamp of last updated article. This is saved as a cookie in front-end and on page load the value in the users session is compared to the value from the plugin. If these don't match then the cookie is reset.

Not really worked on this kind of plugin before so some really useful feedback and suggestions, thanks!

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.