* * @since 1.0 * * @method EasyAddressFieldSettingsModel getSettings() */ class EasyAddressField extends Plugin { public bool $hasCpSettings = true; protected array $fieldTypes = [EasyAddressFieldField::class]; protected array $styles = [ __DIR__.'/../resources/dist/css/leaflet.css' => 'css/leaflet.css', __DIR__.'/../resources/dist/css/EasyAddressField.css' => 'css/EasyAddressField.css', ]; protected array $scripts = [ __DIR__.'/../resources/dist/js/leaflet.js' => 'js/leaflet.js', __DIR__.'/../resources/dist/js/EasyAddressField.js' => 'js/EasyAddressField.js', ]; protected array $publishables = [ __DIR__.'/../resources/dist/css/images' => 'css/images', ]; public FieldService $field { get => app(FieldService::class); } public GeoLocationService $geoLocation { get => app(GeoLocationService::class); } public CountriesService $countries { get => app(CountriesService::class); } public function boot(UiControlTypes $controlTypes): void { $this->app->singleton(EasyAddressFieldSettingsModel::class, fn () => $this->getSettings()); $controlTypes->register(AddressControl::class); // Keeps `craft.address.countries()` working in templates CraftVariable::macro('address', fn () => new class { /** @return array */ public function countries(): array { return app(CountriesService::class)->getCountriesAsArray(); } }); Event::listen(ElementSaving::class, function (ElementSaving $event) { if ($event->element instanceof Address && $this->getSettings()->enableGeoCodingForCraftElements && ! ElementHelper::isDraftOrRevision($event->element)) { $this->geoLocation->locateElement($event->element); } }); } public function getField(): FieldService { return $this->field; } public function geoLocation(): GeoLocationService { return $this->geoLocation; } protected static function createSettings(): ?PluginSettings { return new EasyAddressFieldSettingsModel; } public function settingsUi(UiContext $context = new UiContext): ?Ui { $geoCoders = $this->geoLocation->geoCoders ->map(fn ($geoCoder, string $handle) => ['label' => (string) $geoCoder->name, 'value' => $handle]) ->values() ->all(); return Ui::make([ Field::make(t('Geocoding service', category: 'easy-address-field'), Choice::make('geoCodingService')->options($geoCoders)) ->instructions(t('The geocoding service used, defaults to Nomanatim', category: 'easy-address-field')), Field::make(t('Google API Key for geocoding requests', category: 'easy-address-field'), Text::make('googleApiKey')->textExpanderTriggers(SelectOptions::getEnvTextExpanderTriggers())) ->instructions(t('Only needed if you are using Google as the geocoding service. Environment variables like `$GOOGLE_API_KEY` are supported.', category: 'easy-address-field')), Field::make(t('Enable geocoding for Craft Address fields/elements', category: 'easy-address-field'), Lightswitch::make('enableGeoCodingForCraftElements')), ]); } }