peris
peris

Reputation: 953

Addaptive Symfony2 form choice

i've just created a form class type which has a choice type where the choice_list must change depending on the logged user role, so the form class type needs access to the current user role and then change the choice_list according to it.

Could someone point to a neat way to accomplish it through Symfony2 form patterns?

Upvotes: 2

Views: 294

Answers (2)

ghaliano
ghaliano

Reputation: 415

Here's another way to do it:

 /** @DI\FormType */ 

class ModelType extends AbstractType { 

/** @DI\Inject("security.context") */ 

public $security;

Upvotes: 0

Elnur Abdurrakhimov
Elnur Abdurrakhimov

Reputation: 44831

You need to register the form type as a service and get the security context via the constructor. If you have JMSDiExtraBundle installed, this is how you do it:

<?php
namespace ...;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Security\Core\SecurityContextInterface;
use JMS\DiExtraBundle\Annotation\FormType;
use JMS\DiExtraBundle\Annotation\InjectParams;
use JMS\DiExtraBundle\Annotation\Inject;

/**
 * @FormType
 */
class YourType extends AbstractType
{
    /**
     * @InjectParams({
     *     "securityContext" = @Inject("security.context")
     * })
     *
     * @var SecurityContextInterface
     */
    public function __construct(SecurityContextInterface $securityContext)
    {
        $this->securityContext = $securityContext;
    }

    /**
     * @return string
     */
    public function getName()
    {
        return 'your_type';
    }
}

This way you can get everything you need from the security context.

Since the form is registered as a service, use its name instead of its class when creating a form:

$form = $this->createForm('your_type', /* ... */);

Upvotes: 5

Related Questions