仅在未授权用户时添加自定义表单类型

I have created a custom form type - RecaptchaType. I added it into many forms using $builder->add('recaptcha', RecaptchaType::class). For view I have created a macro, so in twig I render it as follows {{ forms.recaptcha(form.recaptcha) }}.

But now I want to display recaptcha only for users who are not logged in. In twig macro I can simple add if condition. But how can I achieve not adding (or removing) recaptcha input in form type if I want to edit only RecaptchaType and don't want to touch form types, which are using this.

I had two ideas, but neither of them did work.

  • In RecaptchaType use function buildForm and do $builder->remove('recaptcha') when condition is met (user is logged in)
  • Pass option 'render' to $resolver->setDefaults(), access it in form and depend on value do ->add or not. But I can't access the value.

How would you do that? I can add code example if needed.

TL;DR; To remove a form type conditionally encapsulating this logic within itself, you can do the follows:

RecaptchaType:

public function buildForm(FormBuilderInterface $builder, array $options)
{
    $builder->addEventListener(FormEvents::PRE_SET_DATA, function (FormEvent $event) {
        if ($this->isAuthenticated()) {
            $form = $event->getForm();
            $form->getParent()->remove($form->getName());
        }
    });
}

Now, if you are customizing the form theme make sure to check the existence of the field before render it:

{% if form.recaptcha is defined %}
    {{ forms.recaptcha(form.recaptcha) }}
{% endif %}

It should work as long as your RecaptchaType is embedded into another form.