nystudio107/craft-autocomplete

Add generator events

Closed this issue · 7 comments

It would be helpful to have events in AutocompleteVariableGenerator and AutocompleteTwigExtensionGenerator that make it easy to add properties to AutocompleteVariable and globals to AutocompleteTwigExtension respectively.

The usage would be as follows.

use nystudio107\autocomplete\generators\AutocompleteVariableGenerator;
use yii\base\Event;

Event::on(AutocompleteVariableGenerator::class,
    AutocompleteVariableGenerator::EVENT_BEFORE_GENERATE,
    function(Event $event) {
        $event->data[MyClass::class] = 'myClass';
    }
);
use nystudio107\autocomplete\generators\AutocompleteTwigExtensionGenerator;
use yii\base\Event;

Event::on(AutocompleteTwigExtensionGenerator::class,
    AutocompleteTwigExtensionGenerator::EVENT_BEFORE_GENERATE,
    function(Event $event) {
        $event->data['myValue'] = 'hello';
    }
);

What would the use-case be here? Shouldn't it automatically be picking up any variables/globals?

Yes, it should. But say I have a variable called myEntry that is defined in many of my templates (via a controller or in the template itself), it would be nice to be able to add autocompletion for it as follows.

Event::on(AutocompleteTwigExtensionGenerator::class,
    AutocompleteTwigExtensionGenerator::EVENT_BEFORE_GENERATE,
    function(Event $event) {
        $event->data['myEntry'] = 'new \craft\elements\Entry()';
    }
);

IMO it'd be easier to just add a typehint to Twig than write PHP code to do the above:

{# @var cart \craft\commerce\elements\Order #}

e.g.: https://github.com/craftcms/commerce/blob/develop/example-templates/src/shop/cart/index.twig#L5

...but I'm not against the idea of having events anyway, so have at it!

I didn't know that was even possible, very cool!

In my use-case, the variable is used in multiple templates across the site, so I think that adding it via an event makes sense, plus it can't hurt to provide events in general. Thanks for your input!

Added in bba1951, feel free to review.

Did some minor cleanup (most unrelated to the changes). Should be good to go.

Released in 1.0.5.