Based on google reCaptcha API 2.0., (*1)
Installation
The preferred way to install this extension is through composer., (*2)
php composer.phar require --prefer-dist "alikdex/yii2-recaptcha" "2.0.0"
or add, (*3)
"alikdex/yii2-recaptcha" : "2.0.0"
to the require
section of your application's composer.json
file., (*4)
-
Sign up for an reCAPTCHA API keys., (*5)
-
Configure the component in your configuration file (web.php). The parameters siteKey and secret are optional.
But if you leave them out you need to set them in every validation rule and every view where you want to use this widget.
If a siteKey or secret is set in an individual view or validation rule that would overrule what is set in the config., (*6)
'components' => [
'container' => [
'definitions' => [
Adx\ReCaptcha\ReCaptcha::class => [
'siteKey' => 'Your site key',
],
Adx\ReCaptcha\ReCaptchaValidator::class => [
'secret' => 'Your secret key',
],
],
],
...
],
- Add
ReCaptchaValidator
in your model, for example:
public $reCaptcha;
public function rules()
{
return [
// ...
[['captcha'], \Adx\ReCaptcha\ReCaptchaValidator::class],
];
}
or just, (*7)
public function rules()
{
return [
// ...
[[], \Adx\ReCaptcha\ReCaptchaValidator::class],
];
}
Usage
For example:, (*8)
<?= \Adx\ReCaptcha\ReCaptcha::widget([
'name' => 'captcha', // optional
'widgetOptions' => [
'class' => 'col-sm-offset-3',
'data-theme' => 'dark',
// ... see google recaptcha2 manual
]
]) ?>
or, (*9)
<?= $form->field($model, 'captcha')->widget(\Adx\ReCaptcha\ReCaptcha::class) ?>
or simply, (*10)
<?= \Adx\ReCaptcha\ReCaptcha::widget() ?>
Resources