I’m writing a plugin and need some of its settings to be pulled from the .env
file. According to the docs the following should work, but the getter isn’t getting called whenever the plugin’s youtubeApiKey
setting is requested; it just keeps returning $YOUTUBE_API_KEY
.
When I set the property visibility to protected
instead of public
, it does call the getter but also reveals the (sensitive) key in he admin settings panel.
class Settings extends Model
{
public $youtubeApiKey = '$YOUTUBE_API_KEY';
public function getYoutubeApiKey(): string
{
return Craft::parseEnv($this->youtubeApiKey);
}
public function behaviors()
{
return [
'parser' => [
'class' => EnvAttributeParserBehavior::class,
'attributes' => ['youtubeApiKey'],
],
];
}
public function rules()
{
return [
[['youtubeApiKey'], 'string'],
[['youtubeApiKey'], 'default', 'value' => ''],
];
}
}
I suppose my understanding of the settings getters is incorrect, but what I’m trying to achieve is for MyPlugin::getInstance()->getSettings()->youtubeApiKey
to return the actual API key (not $YOUTUBE_API_KEY
) and for the settings field (below) to display $YOUTUBE_API_KEY
(not the actual API key).
{{ forms.textField({
'id': 'youtubeApiKey',
'label': 'YouTube API key',
'name': 'youtubeApiKey',
'suggestEnvVars': true,
'value': settings.youtubeApiKey
}) }}