Plugin settings using env variables not being parsed #13929
-
I have a plugin with a settings model and a CP settings page <?php
use craft\base\Model;
use craft\helpers\App;
use craft\behaviors\EnvAttributeParserBehavior;
class Settings extends Model
{
// Public Properties
// =========================================================================
public string $clientId;
// Public Methods
// =========================================================================
public function defineRules(): array
{
return [
[['clientId'], 'required'],
];
}
public function behaviors(): array
{
return [
'parser' => [
'class' => EnvAttributeParserBehavior::class,
'attributes' => ['clientId'],
],
];
}
public function getClientId(): string
{
return App::parseEnv($this->clientId);
}
} The settings page allows env vars to be used {{ forms.autosuggestField({
label: 'Client ID',
id: 'client-id',
name: 'clientId',
value: settings.clientId,
suggestEnvVars: true,
required: true,
errors: settings.getErrors('clientId')
})
}} When calling for these settings in a service class I just get the env var string output e.g. $CLIENT_ID instead of the actual ID such as 'ABC123'. .env CLIENT_ID=ABC123 Service class echo Plugin::getInstance()->getSettings()->clientId; // $CLIENT_ID output instead of 'ABC123' Can anyone spot where I've gone wrong here? |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
Right – The easy fix for this would be to add a new use craft\helpers\App;
public function getParsedClientId(): string
{
return App::parseEnv($this->clientId);
} And start calling that instead of Alternatively, you could make private string $clientId;
public function getClientId(bool $parse = true): string
{
if ($parse) {
return App::parseEnv($this->clientId);
}
return $this->clientId;
}
public function setClientId(string $clientId): void
{
$this->clientId = $clientId;
}
public function attributes(): array
{
return array_merge(parent::attributes(), [
'clientId',
]);
} With that, {{ forms.autosuggestField({
label: 'Client ID',
id: 'client-id',
name: 'clientId',
value: settings.getClientId(false),
suggestEnvVars: true,
required: true,
errors: settings.getErrors('clientId')
})
}} |
Beta Was this translation helpful? Give feedback.
Right –
Settings:$clientId
is going to store the raw value.The easy fix for this would be to add a new
getParsedClientId()
method:And start calling that instead of
->clientId
directly.Alternatively, you could make
$clientId
a private property and add a magic getter and setter for it, which handles the parsing internally by default, but also providing a way to access the raw value when needed (when rendering the plugin settings form).