2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

CraftCMSのプラグイン設定画面で.envの値をサジェストする

Posted at

CraftCMSで独自プラグインやモジュールを開発する際に、外部サービスのAPIキーやメールアドレスなどを設定することがあります。この設定に.envの値を利用することができますが、設定じに、サジェストしてユーザが選択しやすいようにすることができます。

サジェスト機能付きテキストフィールド設定

templates/settings.twig
{% import "_includes/forms" as forms %}

{{ forms.autosuggestField({
    label: "Secret Key"|t('plugin-handle'),
    id: 'secret-key',
    name: 'secretKey',
    value: settings.secretKey,
    suggestAliases: true,
    suggestEnvVars: true
}) }}

forms.autosuggestField を使うことで、サジェスト機能付きのテキストフィールドを出力できます。これに suggestEnvVars: true をオプションに追加すると、テキストフィールドで先頭に$を入力すると.envの値を参照してサジェストしてくれます。設定値がファイルパスやURLなどの場合は suggestAliases: true もオプションに追加します。

Screen Shot 2020-05-18 at 10.27.41.png

***_PASSWORDや***_KEY、***_SECRETなどは自動でマスクしてくれる模様。サジェストされた環境変数を選択して保存すると、$SOME__KEY 、つまり環境変数名 が保存されます。

環境変数名から値を取得する

上記の通り、保存された設定内容は 環境変数名 になります。このままだと、.envの値を利用できません。環境変数名から.envの値を取得するには、getenv()を使うのではなく、以下のように記述します。

Craft::parseEnv(MyPlugin::getInstance()->settings->secretKey);

Craft::parseEnv()を利用すると、$からスタートする値は.envの値、それ以外はその値そのものを返します。 

2
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?