Craft CMS Poll plugin v1.3.0
Easily make polls in craft cms
More Craft plugins

Poll Events

PollSubmittedEvent - cache your results

The poll submitted event is triggered after a vote has been triggered for a poll.
It is useful for invalidating caches, or do extra registration.

The event includes:

  • The poll entry that was being voted on
  • The answers that were submitted
  • The user (or null) who voted

On heavy sites or polls with lots of submissions, you'd want to cache poll result display to save database queries and processing time.

Here is an example using the nice cache flag plugin (https://github.com/mmikkel/Cac...), where poll results are cached and only updated if a user has voted on a poll.


PHP: In your app's module or plugin, register an event listener in the init method. If you use a module, don't forget to bootstrap it in config/app.php
modules/Module.php:
use craft\elements\Entry;
use mmikkel\cacheflag\CacheFlag;
use twentyfourhoursmedia\poll\events\PollEvents;
use twentyfourhoursmedia\poll\events\PollSubmittedEvent;

...
    init() {
        ...
        Event::on(Entry::class, PollEvents::POLL_SUBMITTED, function(PollSubmittedEvent $event) {
           CacheFlag::$plugin->cacheFlag->deleteFlaggedCachesByFlags('poll');
        });
        ...
    }
Twig: Display cached poll results using cacheflag
{% cacheflag flagged "poll" %}
    {% set results = poll | poll_results({
        with_users: true,
        user_id_only: false,
        limit_users: 1000
    }) %}

    {# display the results here, they will be cached by cacheflag and refreshed if any poll is voted on #}

{% endcacheflag %}