Coder1
Coder1

Reputation: 13321

Conditionally display form field in Symfony 3

I have an account (like company account) entity with a user association for the accountOwner.

Both account owner and users with ROLE_ADMIN can edit the account, but only users with ROLE_ADMIN can set the account owner.

Do I need 2 form types? or can I conditionally present the accountOwner field on the same form based on user role?

Upvotes: 1

Views: 3851

Answers (1)

Igor Pantović
Igor Pantović

Reputation: 9246

You can present accountOwner association conditionally. When you want to modify form dynamically, you'll usually want to use form events.

However, since your form's fields do not depend on actual data bound to the form, but on security context, you can just inject authorization checker into your form type and check whether you want to add needed field:

public function buildForm(FormBuilderInterface $builder, array $options)
{
    $builder->add('always_present_field');
    $builder->add('another_always_present_field');

    if ($this->authorizationChecker->isGranted('ROLE_ADMIN')) {
        $builder->add('conditional_field_if_current_user_is_admin');
    }
}

Upvotes: 4

Related Questions