Code Monkey home page Code Monkey logo

ewzrecaptchabundle's Introduction

EWZRecaptchaBundle

Actions Status

This bundle provides easy reCAPTCHA form field for Symfony.

Installation

Step 1: Use composer and enable Bundle

To install EWZRecaptchaBundle with Composer just type in your terminal:

php composer.phar require excelwebzone/recaptcha-bundle

Now, Composer will automatically download all required files, and install them for you. All that is left to do is to update your AppKernel.php file, and register the new bundle:

<?php

// in AppKernel::registerBundles()
$bundles = array(
    // ...
    new EWZ\Bundle\RecaptchaBundle\EWZRecaptchaBundle(),
    // ...
);

Step2: Configure the bundle's

NOTE: The configuration options differ between Version 2 and Version 3 of the reCAPTCHA system. Some of the previous options have no effect on Version 3.

Add the following to your config file:

NOTE: If you're using symfony 4, the config will be in config/packages/ewz_recaptcha.yaml. The local dev enviroment has its own config in config/packages/dev/ewz_recaptcha.yaml.

Main configuration for both v2 and v3

The version setting determines which configuration options are available. Set the version corresponding to your Google reCAPTCHA settings (valid values: 2 or 3):

# app/config/config.yml

ewz_recaptcha:
    // ...
    version: 2

You can easily disable reCAPTCHA (for example in a local or test environment):

# app/config/config.yml

ewz_recaptcha:
    // ...
    enabled: false

Enter the public and private keys here:

# app/config/config.yml

ewz_recaptcha:
    // ...
    public_key:  here_is_your_public_key
    private_key: here_is_your_private_key

www.google.com is blocked in Mainland China, you can override the default server like this (See https://developers.google.com/recaptcha/docs/faq#can-i-use-recaptcha-globally for further information):

# app/config/config.yml

ewz_recaptcha:
    // ...
    api_host: recaptcha.net

You can add HTTP Proxy configuration:

# app/config/config.yml

ewz_recaptcha:
    // ...
    http_proxy:
        host: proxy.mycompany.com
        port: 3128
        auth: proxy_username:proxy_password

v2 only Configuration

Sets the default locale:

# app/config/config.yml

ewz_recaptcha:
    // ...
    # Not needed as "%kernel.default_locale%" is the default value for the locale key
    locale_key:  %kernel.default_locale%

NOTE: This Bundle lets the client browser choose the secure https or unsecure http API.

If you want to use the language default for the reCAPTCHA the same as the request locale you must activate the resolver (deactivated by default):

# app/config/config.yml

ewz_recaptcha:
    // ...
    locale_from_request: true

You can load the reCAPTCHA using Ajax:

# app/config/config.yml

ewz_recaptcha:
    // ...
    ajax: true

In case you have turned off the domain name checking on reCAPTCHA's end, you'll need to check the origin of the response by enabling the verify_host option:

# app/config/config.yml

ewz_recaptcha:
    // ...
    verify_host: true

NOTE: If you're using symfony 5 and want to configure the bundle with PHP files instead of YAML, the configuration is like this:

// config/packages/ewz_recaptcha.php

<?php declare(strict_types=1);

use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;

return static function (ContainerConfigurator $configurator): void
{
    $configurator->extension('ewz_recaptcha', [
        'public_key' => 'here_is_your_public_key',
        'private_key' => 'here_is_your_private_key',
        'locale_key' => '%kernel.default_locale%'
    ]);
};

v3 only Configuration

For the v3 reCAPTCHA an information badge is shown. If you inform your users about using the reCAPTCHA on another way, you can hide it with the following option (see https://developers.google.com/recaptcha/docs/faq#hiding-badge for further information):

# app/config/config.yml

ewz_recaptcha:
    // ...
    hide_badge: true

To modify the default threshold score of 0.5 set this option (see https://developers.google.com/recaptcha/docs/v3#interpreting_the_score for further information):

# app/config/config.yml

ewz_recaptcha:
    // ...
    score_threshold: 0.6

Congratulations! You're ready!

Basic Usage

NOTE: The basic usage differs between Version 2 and Version 3 of the reCAPTCHA system.

v2 Usage

When creating a new form class add the following line to create the field:

<?php

use EWZ\Bundle\RecaptchaBundle\Form\Type\EWZRecaptchaType;

public function buildForm(FormBuilder $builder, array $options)
{
    // ...
    $builder->add('recaptcha', EWZRecaptchaType::class);
    // ...
}

Note that in Symfony versions lower than 2.8 refers to form types by name instead of class name, use:

<?php

public function buildForm(FormBuilder $builder, array $options)
{
   // ...
   $builder->add('recaptcha', 'ewz_recaptcha');
   // ...
}

You can pass extra options to reCAPTCHA with the "attr > options" option:

<?php

use EWZ\Bundle\RecaptchaBundle\Form\Type\EWZRecaptchaType;

public function buildForm(FormBuilder $builder, array $options)
{
    // ...
    $builder->add('recaptcha', EWZRecaptchaType::class, array(
        'attr' => array(
            'options' => array(
                'theme' => 'light',
                'type'  => 'image',
                'size'  => 'normal',
                'defer' => true,
                'async' => true,
            )
        )
    ));
    // ...
}

Support Google's Invisible is super easy:

<?php

public function buildForm(FormBuilder $builder, array $options)
{
    // ...
    $builder->add('recaptcha', EWZRecaptchaType::class, array(
        'attr' => array(
            'options' => array(
                'theme' => 'light',
                'type'  => 'image',
                'size' => 'invisible',              // set size to invisible
                'defer' => true,
                'async' => true,
                'callback' => 'onReCaptchaSuccess', // callback will be set by default if not defined (along with JS function that validate the form on success)
                'bind' => 'btn_submit',             // this is the id of the form submit button
                // ...
             )
        )
    ));
    // ...
}

Note: If you use the pre-defined callback, you would need to add recaptcha-form class to your <form> tag.

If you need to configure the language of the captcha depending on your site language (multisite languages) you can pass the language with the "language" option:

<?php

public function buildForm(FormBuilder $builder, array $options)
{
    // ...
    $builder->add('recaptcha', EWZRecaptchaType::class, array(
        'language' => 'en'
        // ...
    ));
    // ...
}

To validate the field use:

<?php

use EWZ\Bundle\RecaptchaBundle\Validator\Constraints as Recaptcha;

/**
 * @Recaptcha\IsTrue
 */
public $recaptcha;

Another method would consist to pass the validation constraints as an options of your FormType. This way, your data class contains only meaningful properties. If we take the example from above, the buildForm method would look like this. Please note that if you set mapped=>false then the annotation will not work. You have to also set constraints:

<?php

use EWZ\Bundle\RecaptchaBundle\Form\Type\EWZRecaptchaType;
use EWZ\Bundle\RecaptchaBundle\Validator\Constraints\IsTrue as RecaptchaTrue;

public function buildForm(FormBuilder $builder, array $options)
{
    // ...
    $builder->add('recaptcha', EWZRecaptchaType::class, array(
        'attr'        => array(
            'options' => array(
                'theme' => 'light',
                'type'  => 'image',
                'size'  => 'normal'
            )
        ),
        'mapped'      => false,
        'constraints' => array(
            new RecaptchaTrue()
        )
    ));
    // ...

The form template resource is now auto registered via an extension of the container. However, you can always implement your own custom form widget.

PHP:

<?php $view['form']->setTheme($form, array('EWZRecaptchaBundle:Form')) ?>

<?php echo $view['form']->widget($form['recaptcha'], array(
    'attr' => array(
        'options' => array(
            'theme' => 'light',
            'type'  => 'image',
            'size'  => 'normal'
        ),
    ),
)) ?>

Twig:

{% form_theme form '@EWZRecaptcha/Form/ewz_recaptcha_widget.html.twig' %}

{{ form_widget(form.recaptcha, { 'attr': {
    'options' : {
        'theme': 'light',
        'type': 'image',
        'size': 'normal'
    },
} }) }}

If you are not using a form, you can still implement the reCAPTCHA field using JavaScript:

PHP:

<div id="recaptcha-container"></div>
<script type="text/javascript">
    $(document).ready(function() {
        $.getScript("<?php echo \EWZ\Bundle\RecaptchaBundle\Form\Type\EWZRecaptchaType::RECAPTCHA_API_JS_SERVER ?>", function() {
            Recaptcha.create("<?php echo $form['recaptcha']->get('public_key') ?>", "recaptcha-container", {
                theme: "clean",
            });
        });
    };
</script>

Twig:

<div id="recaptcha-container"></div>
<script type="text/javascript">
    $(document).ready(function() {
        $.getScript("{{ constant('\\EWZ\\Bundle\\RecaptchaBundle\\Form\\Type\\EWZRecaptchaType::RECAPTCHA_API_JS_SERVER') }}", function() {
            Recaptcha.create("{{ form.recaptcha.get('public_key') }}", "recaptcha-container", {
                theme: "clean"
            });
        });
    });
</script>

Customization

If you want to use a custom theme, put your chunk of code before setting the theme:

 <div id="recaptcha_widget">
   <div id="recaptcha_image"></div>
   <div class="recaptcha_only_if_incorrect_sol" style="color:red">Incorrect please try again</div>

   <span class="recaptcha_only_if_image">Enter the words above:</span>
   <span class="recaptcha_only_if_audio">Enter the numbers you hear:</span>

   <input type="text" id="recaptcha_response_field" name="recaptcha_response_field" />

   <div><a href="javascript:Recaptcha.reload()">Get another CAPTCHA</a></div>
   <div class="recaptcha_only_if_image"><a href="javascript:Recaptcha.switch_type('audio')">Get an audio CAPTCHA</a></div>
   <div class="recaptcha_only_if_audio"><a href="javascript:Recaptcha.switch_type('image')">Get an image CAPTCHA</a></div>

   <div><a href="javascript:Recaptcha.showhelp()">Help</a></div>
 </div>

{% form_theme form '@EWZRecaptcha/Form/ewz_recaptcha_widget.html.twig' %}

{{ form_widget(form.recaptcha, { 'attr': {
    'options' : {
        'theme' : 'custom',
    },
} }) }}

v3 Usage

When creating a new form class add the following line to create the field:

<?php

use EWZ\Bundle\RecaptchaBundle\Form\Type\EWZRecaptchaV3Type;

public function buildForm(FormBuilder $builder, array $options)
{
    // ...
    $builder->add('recaptcha', EWZRecaptchaV3Type::class);
    // ...
}

You can pass the action to reCAPTCHA with the "action_name" option (see https://developers.google.com/recaptcha/docs/v3#actions for further information)::

<?php

use EWZ\Bundle\RecaptchaBundle\Form\Type\EWZRecaptchaType;

public function buildForm(FormBuilder $builder, array $options)
{
    // ...
    $builder->add('recaptcha', EWZRecaptchaType::class, array(
        'action_name' => 'contact'
    ));
    // ...
}

To validate the field use:

<?php

use EWZ\Bundle\RecaptchaBundle\Validator\Constraints as Recaptcha;

/**
 * @Recaptcha\IsTrueV3
 */
public $recaptcha;

Another method would consist to pass the validation constraints as an options of your FormType. This way, your data class contains only meaningful properties. If we take the example from above, the buildForm method would look like this. You have to also set constraints:

<?php

use EWZ\Bundle\RecaptchaBundle\Form\Type\EWZRecaptchaV3Type;
use EWZ\Bundle\RecaptchaBundle\Validator\Constraints\IsTrueV3;

public function buildForm(FormBuilder $builder, array $options)
{
    // ...
    $builder->add('recaptcha', EWZRecaptchaV3Type::class, array(
        'action_name' => 'contact',
        'constraints' => array(
            new IsTrueV3()
        )
    ));
    // ...

Advanced Usage

It is possible to register reCAPTCHA form services. To accomplish this, enter the service definition as follows (in this example we did it in PHP):

<?php

$ewzRecaptchaConfiguration = array();
$ewzRecaptchaConfiguration['enabled'] = isset($_ENV['RECAPTCHA_PUBLIC'], $_ENV['RECAPTCHA_PRIVATE']);
$ewzRecaptchaConfiguration['public_key'] = $_ENV['RECAPTCHA_PUBLIC'] ?? null;
$ewzRecaptchaConfiguration['private_key'] = $_ENV['RECAPTCHA_PRIVATE'] ?? null;
$ewzRecaptchaConfiguration['api_host'] = 'recaptcha.net';
$ewzRecaptchaConfiguration['version'] = 3;

$ewzRecaptchaConfiguration['service_definition'] = array();
$ewzRecaptchaConfiguration['service_definition'][] = [
    'service_name' => 'ContactRecaptchaService',
    'options' => [
        'action_name' => 'form'
    ]
];

// Add more form services here

// ...
$container->loadFromExtension('ewz_recaptcha', $ewzRecaptchaConfiguration);
// ...

Now the services are now accessible with ewz_recaptcha.[service_name]. They can be registered to your form type class:

<?php

namespace MyNamespace\DependencyInjection;

use MyNamespace\Form\ContactType;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Reference;
use Symfony\Component\DependencyInjection\Extension\Extension;

class ContactFormExtension extends Extension
{

    public function load(array $configs, ContainerBuilder $container)
    {
        $container->register(ContactType::class)
            ->addArgument(new Reference('ewz_recaptcha.ContactRecaptchaService'))
            ->addTag('form.type');
    }
}
// ...

The form type class itself uses the injected service this way:

<?php

namespace MyNamespace\Form;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;

class ContactType extends AbstractType
{
    /** @var FormBuilderInterface */
    private $recaptcha;

    public function __construct(?FormBuilderInterface $recaptcha)
    {
        $this->recaptcha = $recaptcha;
    }

    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        // ...
        if(null !== $this->recaptcha) {
            $builder->add($this->recaptcha);
        }
        // ...
    }

ewzrecaptchabundle's People

Contributors

adityapatadia avatar aleho avatar biozshock avatar bobvandevijver avatar damienalexandre avatar diegotham avatar doncallisto avatar efarya avatar excelwebzone avatar franmomu avatar gelolabs avatar grifx avatar jbgomond avatar jbouzekri avatar lerminou avatar manuxi avatar mbabker avatar moesoha avatar ne-lexa avatar oskarstark avatar pborreli avatar petk avatar picks44 avatar pulzarraider avatar quingkhaos avatar sander-toonen avatar seb33300 avatar snamor avatar sstok avatar stanlemon avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

ewzrecaptchabundle's Issues

Error in latest revisions

Hi, I tried to send an email via [email protected], but getting recipient not found so thought I'd report this here.

On attempting to run an update of symfony 3'rd party vendors, the following error appears :

[Symfony\Component\DependencyInjection\Exception\ServiceNotFoundException]
The service "ewz_recaptcha.validator.true" has a dependency on a non-existent service "request_stack".

Is anyone aware of this problem and how can this be solved ?

Prepend Form Theme Instead of Appending

Currently this bundle appends its form theme to Symfony's twig.form.resources parameter, which overrides all themes specified in the main config.yml file. When I need to override the default widget output everywhere in my application, I have to manually reference my overriding theme via form_theme everywhere I use a form.

I think it would make more sense to prepend the theme to defined themes, allowing global themes to override it as necessary.

(My use case is loading pages dynamically in a "one-page application". I manually render each widget as its loaded into the page.)

Recaptcha not displaying form errors

Hi.
The bundle is working fine but when the validation fails no error message is shown. The error messages are showing correctly for all the other fields of the form.

Any ideas what I am doing wrong?
Using Symfony 2.2.4.

My form definition:

 $builder->add('recaptcha', 'ewz_recaptcha', array(
        'label' => 'register_user.form.labels.captcha',     
        'attr' => array(
            'options' => array(
                'theme' => 'clean'
            )
        ),
        'mapped' => false,
        'constraints'   => array(
            new True()
        ),

Render:

{{ form_row(registerUserForm.recaptcha) }}

Change language dynamically

Hi, i have a website that works in 2 languages, is it possible to set language dyanmically instead of it being hardcoded in config?

Update

I found a solution, here is what i did:

  1. Add custom RecaptchaType In config parameters (config.yml)
parameters:
    ewz_recaptcha.form.type.class: My\NameBundle\Form\RecaptchaType
  1. Inherit from the bundle's RecaptchaType and Redefine buildView method:
namespace My\NameBundle\Form;

use EWZ\Bundle\RecaptchaBundle\Form\Type\RecaptchaType as BaseRecaptchaType;
use Symfony\Component\Form\FormInterface;
use Symfony\Component\Form\FormView;

/**
 * Class RecaptchaType
 * @package My\NameBundle\Form
 */
class RecaptchaType extends BaseRecaptchaType {

    public function buildView(FormView $view, FormInterface $form, array $options)
    {
        $this->language = isset($view->vars['attr']['language']) ? $view->vars['attr']['language'] : $this->language;
        parent::buildView($view, $form, $options);
    }
}
  1. Finally when building your form add language to the passed attributes:
$builder->add('recaptcha', EWZRecaptchaType::class, array(
        'attr' => array(
           'language' => $Your_Dynamically_Detected_Language
            'options' => array(
                'theme' => 'light',
                'type'  => 'image'
            )
        )
    ));

Remove the customisation and ajax

As the new google captcha does not support customisation we should remove the documentation and support for the same from this bundle. Apart from that, ajax option has also lost relevance so it should be removed. Let me know your views @excelwebzone

Add some options in the form builder

Is it possible to add more options like "enable" or "secure" in the ewz_recaptcha element inside the buildForm function? For example:

public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('recaptcha', 'ewz_recaptcha', array(
'attr' => array(
'options' => array(
// other options like theme, lang and custom_translations
'secure' => true, // the new option
),
),
'mapped' => false,
// constraints and more
));
}

And then in the RecaptchaType file, it could be like this:

public function buildView(FormView $view, FormInterface $form, array $options)
{
$view->vars = array_replace($view->vars, array(
'ewz_recaptcha_enabled' => $this->enabled,
));

if (!$this->enabled) {
    return;
}

/* New code */
if (isset($options['attr'])) {
    $attr = $options['attr'];

    if (isset($attr['options']) && !is_null($attr['options'])) {
        $options = $attr['options'];

        if (isset($options['secure'])) {
            $this->secure = $options['secure'];
        }
    }
}
/* End code */

if ($this->secure) {
    $server = self::RECAPTCHA_API_SECURE_SERVER;
} else {
    $server = self::RECAPTCHA_API_SERVER;
}

$view->vars = array_replace($view->vars, array(
    'url_challenge' => sprintf('%s/challenge?k=%s', $server, $this->publicKey),
    'url_noscript'  => sprintf('%s/noscript?k=%s', $server, $this->publicKey),
    'public_key'    => $this->publicKey,
));

}

Thank you

EWZRecaptchaType;

Add this to Basic Usage:

use EWZ\Bundle\RecaptchaBundle\Form\Type\EWZRecaptchaType;

Tested on Symfony 3.0.1

Update readme

Class EWZRecaptchaType does not even exist in your code. Update readme =.="

Never validate recaptcha field

I'm using Symfony 2.7 and I'm trying to use this bundle (dev-master) in my registration form. I have followed the steps of documentation but it's not work, never validate the recaptcha field.

I've configured the bundle

ewz_recaptcha:
    public_key:  my_public_key
    private_key: my_private_key
    locale_key:  %kernel.default_locale%

I've added recaptcha in my class Register:

// ...
use EWZ\Bundle\RecaptchaBundle\Validator\Constraints as Recaptcha;

class Register
{
    // ...

    /**
     * @Recaptcha\IsTrue
     */
    public $recaptcha;

    // ...
}

and in my RegisterType:

// ...
class RegisterType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        // ...  
        ->add('recaptcha', 'ewz_recaptcha');
    }

    public function getName()
    {
        return 'register';
    }
}

and in my form template:

{# ... #}
{{ form_widget(form.recaptcha) }}
{# ... #}

When I submit the form, never show error message "This value is not a valid captcha." although I don't check it. Have I to do something in my controller when I get and valid the form submit?

Thanks.

Symfony 2.3 not possible to access field attribute

According to your documentation it is possible to get recaptacha attributes this way
"get('public_key') ?>"
In Symfony 2.3 there is no function get() on FormView object any more. Instead you have to use this
"vars('public_key') ?>"

Request to google with https

Hello. I have the following error..

Mixed Content: The page at 'https://www.my-domain.net/register' was loaded over HTTPS, but requested an insecure script 'http://www.google.com/recaptcha/api/challenge?k=my_key'. This request has been blocked; the content must be served over HTTPS.

How can I to do a request to captcha https ?

Thanks

Is possible use Symfony2.3 , RecaptchaBundle and new version of google recaptcha ?

I have a project with Symfony2.3

If I use version 2.3 of RecaptchaBundle, my form does not show new recaptcha google.

I need override template to change url:

{{ form.vars.url_challenge }}

by

http://www.google.com/recaptcha/api.js

I overrided this template, so I see the new version of recaptcha, but always in my form I see:

This value is not a valid captcha.

I cannot update version symfony of my project, but I want use this bundle to show new recaptcha !
Any idea ?

Thanks in advance !

Tag a new release

Hi,

Can you tag a new release so I can upgrade my project to >= Symfony 2.8. Currently relies on Frameworkbundle 2.0 when Symfony2.8 ships 3.* of framework bundle.

Thanks

Symfony >= 2.5.12 Error Notice: Undefined index: language

Hi, i had a problem with the EWZRecaptchaBundle on dev-master
Exception emit Notice: Undefined index: language in RecaptchaType.php line 80.

The configureOptions isn't call in RecaptchaType.php line 94 and the default option isn't set instead we must call
setDefaultOptions(OptionsResolverInterface $resolver)

Regards :)

Login Form

Is there an example how to use this inside attemptAuthentication in UsernamePasswordFormAuthenticationListener?

I need to validate captcha against login

Wrong captcha for all my FOSUser form

Hi,

I'm using recaptcha bundle in my fosuser register form. The point is that i have for all my fosuser form the erreur "... wrong captcha" now, but i just add it for the register form.
It comes from the code i put in my entity user.
/**
* @recaptcha\True
*/
public $recaptcha;
When i remove it, it's ok...

Thx

Bug getting language

On RecaptchaType.php, change the constructor to:

public function __construct(ContainerInterface $container)
{
    $this->publicKey = $container->getParameter('ewz_recaptcha.public_key');
    $this->secure    = $container->getParameter('ewz_recaptcha.secure');
    $this->enabled   = $container->getParameter('ewz_recaptcha.enabled');
    $this->language  = $container->getParameter('ewz_recaptcha.locale_key');
}

Symfony 2.3 support

Hi

I use this bundle with the LTS 2.3 Symfony version but it appears you no longer support or even have an old tag for Symfony 2.3

Your composer.json now specifies

  "symfony/framework-bundle": "~2.4"

Any chance you can create a branch that supports 2.3?

Form Error message

I'm using dev-master and added the constraint to the recaptcha field, the RecaptchaTrue one, but if I send the form without filling the captcha, then the error message is added for the main form, not for the captcha field. I tried to use the error_mapping option, but couldn't solve it.

reCaprcha loaded in ajax

Currently there is no way to asynchronously add a rechapta because of the google API used (the error I get in the console is Failed to execute 'write' on 'Document': It isn't possible to write into a document from an asynchronously-loaded external script unless it is explicitly opened.), from the js file http://www.google.com/recaptcha/api/challenge (document.write('<scr'+'ipt type="text/javascript" s'+'rc="' + RecaptchaState.server + 'js/recaptcha_canary.js"></scr'+'ipt>');).

Maybe adding a form option 'ajax' and then using what is written here https://developers.google.com/recaptcha/docs/display?csw=1#AJAX (I'm not an expert in reCaptcha APIs, thou) could help?

Thanks a lot!

I don't want to use Formbuilder

Hello , I want to display the captcha directly from twig or calling the value from my controller and display it on my twig file. I have never used FormBuilder and I do not want to use it now.
Can you help ?

Language settings

I saw, that I can change the locale in the config.yml but I use one symfony instance with multiple locale, changed with the jms_i18n bundle, means that I don't have the current locale in any parameters.
Would it be possible to set the locale through options? And if nothing is set there, then use it from the config.yml?

Specify the width of the capture box

Hi,

Is there anyway to specify the width of the reCAPTCHA box? The width appears as 302px for me, however with the layout and design of my page on mobile this is too wide. I need a width of around 275px. Is this possible to configure?

<div class="g-recaptcha" data-expired-callback="" data-sitekey="" data-type="image" data-theme="light">
   <div>
      <div style="width: 275px; height: 78px;">
         <iframe width="275" height="78" frameborder="0" 
src="https://www.google.com/recaptcha/api2/anchor?k=&co=&hl=en&type=image&v=r20160502112552&theme=light&size=normal&cb=" 
title="recaptcha widget" role="presentation" 
scrolling="no" name="undefined">

I have the reCAPTCHA hooked into my form like this:

            ->add('recaptcha', 'ewz_recaptcha', array(
                'label'         => false,
                'mapped'        => false,
                'constraints'   => array(
                    new Recaptcha\IsTrue(['groups' => 'CRMPiccoPersonalDetails']),
                ),
            ))

...and it is output within Twig like this:

        <div class="panel panel-default">
            <div class="panel-body">
                <div class="row">
                    <div class="recaptcha">
                        <div class="col-sm-12">
                            {{ form_row(form.recaptcha) }}
                        </div>
                    </div>
                </div>
            </div>
        </div>

Many thanks.

Notice: Undefined index: language

Error is coming from RecaptchaType.php, line 80

        if (!$this->ajax) {
            $view->vars = array_replace($view->vars, array(
                'url_challenge' => sprintf('%s?hl=%s', self::RECAPTCHA_API_SERVER, $options['language']),
                'public_key'    => $this->publicKey,
            ));
        } else {

This is present even when language is defined

            ->add('recaptcha', 'ewz_recaptcha', array(
                    'attr' => array(
                        'options' => array(
                            'theme' => 'light',
                            'type'  => 'image',
                            'language' => 'eng',
                        ),
                    )
                ))

reCAPTCHA isn't render if page is loaded trough AJAX

After the latest PR from @EnoahNetzach and the merge from @excelwebzone I tried to work with the bundle and I can't since reCAPTCHA isn't render in the form. This is what I did:

  • Add this line "excelwebzone/recaptcha-bundle": "dev-master" to my composer.json file and after run the command composer update

    Result:

    Loading composer repositories with package information
    Updating dependencies (including require-dev)
      - Updating excelwebzone/recaptcha-bundle dev-master (d821a4f => dce1915)
        Checking out dce19159420c2aa2fa7a38dbee1b54654b53b7fe
    
  • Add this line new EWZ\Bundle\RecaptchaBundle\EWZRecaptchaBundle(), to AppKernel.php

  • Add this to config.yml:

    ewz_recaptcha:
        public_key:   %recaptcha_public_key%
        private_key:  %recaptcha_public_key%
        locale_key:   %kernel.default_locale%
        ajax: true
    
  • Add this to my RegistrationFormType.php where captcha should goes:

    use EWZ\Bundle\RecaptchaBundle\Validator\Constraints\True;
    
    ....
    ->add('captcha', 'ewz_recaptcha', array(
        'attr' => array(
            'options' => array(
                'theme' => 'clean',
                'ajax' => true
            )
        ),
        'mapped' => false,
        'constraints' => array(
            new True()
        )
    ))
    ....
    
  • Render the field in my template:

    {{ form_widget(form.usuario.captcha, {'attr': { 'data-bv-excluded':'true' }}) }}
    

When page load I can see this HTML:

    <div class="col-md-6 col-sm-4">
      <div id="ewz_recaptcha_div"></div>
        <script type="text/javascript">
            $(function() {
                Recaptcha.create('6Ld3TPkSAAAAAPckREYZuVQ6GtjMQsD-Q5CkzNxj', 'ewz_recaptcha_div', {"theme":"clean","ajax":true});
            });
        </script>
    </div>

But not clue around the reCaptcha image as image below shows:

2014-08-28_10-39-38

Did I miss something or bundle still buggy?

Silex : Could not load type "ewz_recaptcha"

after following all the steps , i am still not able to enable captcha.
getting and error.
InvalidArgumentException in FormRegistry.php line 92: Could not load type "ewz_recaptcha"

below are the silex and recaptcha-bundle verison in composer.json
"silex/silex" : "~1.1",
"excelwebzone/recaptcha-bundle": "dev-master"

How to put in french ?

Hello,

Sorry for my english. I see some files in Resources/Translations but how do we use these files ?
I'm a beginner.
I just want to put message in french when code is wrong.

Thank you

Render and validate recaptcha when FormType and FormBuilder not used

Hello, I have a form, and for some reasons I cant use form type, or form builder to create it. So when in Twig template I pass <form> and script for recaptcha from EWZRecaptchaBundle doc, it renders captcha properly but not validate. So the question is, there is exist "bundle-way" to validate form, or I need to write peace of custom javascript ?

Validation is not working.

I´m trying to do this bundle works but I can´t get it. I have followed the steps but I don´t understand exactly how to validate the recaptcha.

My form:

use EWZ\Bundle\RecaptchaBundle\Validator\Constraints\True;

class formContact extends AbstractType {

public function buildForm(FormBuilderInterface $builder, array $options) {
    parent::buildForm($builder, $options);

    $builder->add('Name');
    $builder->add('Email');
    $builder->add('Message', 'textarea', array(
        'attr' => array('rows' => '8')));


   $builder->add('recaptcha', 'ewz_recaptcha', array(
    'attr'          => array(
        'options' => array(
            'theme' => 'clean'
        )
    ),
    'mapped' => false,
    'constraints'   => array(
        new True()
    )
));

}

config:

framework:
validation: { enable_annotations: true }

controller:

$form = $this->createForm(new formContact(), array(
'action' => $this->generateUrl('contact'),
'method' => 'POST'));

    $cloned = clone $form;

    if ($request->getMethod() === 'POST') {

        $form->handleRequest($request);

        $name = $form->get('Name')->getData();
        $mail = $form->get('Email')->getData();
        $mess = $form->get('Message')->getData();

        $message = \Swift_Message::newInstance()
                ->setSubject('')
                ->setFrom('')
                ->setBody(
                $this->render(
                        'MplusgFrontendBundle:Mail:mail.txt.twig', array('name' => $name, 'mail' => $mail, 'message' => $mess)
                )
        );

        $this->get('mailer')->send($message);

// }

        $form = $cloned;

        return $this->render('MplusgFrontendBundle:Default:contact.html.twig', array('form' => $form->createView()));
    }

If you can help me it would be very appreciated.

Allow symfony 2.8 OR 3.0

I cannot use the latest version of the bundle, because the Bundle requires Symfony3 now.
But it should be like ~2.8|~3.0 - I think it wont break anything, just maybe a few deprecation warnings.

Would be awsome to be able to use the language overrride introduced in v.1.4.2.

Should I submit a PR for it?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.