Standard reCAPTCHA and invisible reCAPTCHA form fields for SilverStripe
Standard reCAPTCHA and invisible reCAPTCHA form fields for SilverStripe
Author: Andrew Mc Cormack
For SilverStripe 4.*
Add the following to your composer.json file and run /dev/build?flush=all
{
"require": {
"cyber-duck/silverstripe-recaptcha": "4.0.*"
}
}
Add 2 .env vars with your recaptcha keys
RECAPTCHA_SITE_KEY="0000000000"
RECAPTCHA_SECRET_KEY="0000000000"
Add the field to any form on your site just as you would any other field.
Pass in:
use CyberDuck\Recaptcha\Forms\RecaptchaField;
$fields = FieldList::create([
RecaptchaField::create('Recaptcha');
]);
$validator = RequiredFields::create([
'Recaptcha'
]);
Add 2 .env vars with your recaptcha keys
RECAPTCHA_INVISIBLE_SITE_KEY="0000000000"
RECAPTCHA_INVISIBLE_SECRET_KEY="0000000000"
Add the field to any form on your site just as you would any other field.
Pass in:
use CyberDuck\Recaptcha\Forms\InvisibleRecaptchaField;
$fields = FieldList::create([
InvisibleRecaptchaField::create(
'Recaptcha',
'MemberLoginForm_LoginForm',
'MemberLoginForm_LoginForm_action_doLogin'
);
]);
$validator = RequiredFields::create([
'Recaptcha'
]);
If you would like to use the reCAPTCHA with AJAX you can copy the InvisibleRecaptcha.ss from the module templates folder into your theme templates folder
<script type="text/javascript">
var onRecaptchaFormSubmit = function(token) {
document.getElementById('{$FormID}').submit();
};
var onloadCallback = function() {
grecaptcha.render('{$Container}', {
'sitekey' : '{$SiteKey}',
'callback' : onRecaptchaFormSubmit
});
};
</script>
And just update the onRecaptchaFormSubmit function to use jQuery to select and submit the form
<script type="text/javascript">
var onRecaptchaFormSubmit = function(token) {
$('#{$FormID}').submit();
};
var onloadCallback = function() {
grecaptcha.render('{$Container}', {
'sitekey' : '{$SiteKey}',
'callback' : onRecaptchaFormSubmit
});
};
</script>
In your AJAX success function, if your form fails validation you can call onloadCallback() to re-render the reCAPTCHA
onloadCallback()
Module rating system helping users find modules that are well supported. For more on how the rating system works visit Module standards
Score not correct? Let us know there is a problem