2

I am building a custom validator. In a controller I would get the security context using:

$this->get('security.context')->getToken()->getUser()

I can't manage to do the same in a custom validator; could anyone help me out?

Thanks so much!

Ben
  • 1,095
  • 1
  • 11
  • 14

1 Answers1

4

You either need to extend ContainerAware with your filter class then call setContainer on the class when you instantiate it or pass through the container to the class on construct. This is because filters are not container aware by default like the controller is.

To do it by constructor you can add the __construct method like below to your filter class:

protected $container;

public function __construct($container){
    $this->container = $container;   
}

Either way you will need to use container in your call:

$this->container->get('security.context')->getToken()->getUser()

Check this link https://groups.google.com/forum/?fromgroups#!topic/symfony2/WWIc8N7KZrg for extending container aware idea for doctrine entities, might be of some help.

Edit

Looking at the docs for validator you can add a service if it has any dependencies:

services:
    validator.unique.your_validator_name:
        class: Fully\Qualified\Validator\Class\Name
        tags:
            - { name: validator.constraint_validator, alias: alias_name }

why not add an argument to that for the container:

arguments:  [@security.context] 

and then use the construct method?

protected $security_context;

public function __construct($security_context){
    $this->security_context = $security_context;   
}
Luke
  • 3,333
  • 2
  • 28
  • 44
  • 3
    Injecting the whole container is a Bad Idea. Inject only those services you need — individually. – Elnur Abdurrakhimov Jun 13 '12 at 06:15
  • Thanks so much for the answer. This is a little complicated for what I'm trying to do, so Ill put the validation logic in the controller. – Ben Jun 13 '12 at 06:24
  • @elnur I read this http://stackoverflow.com/questions/7561013/injecting-securitycontext-services-into-a-listener-class-in-symfony2-causes-circ and not sure if you can just get security.context. Do you think you could do `["@security.context"]` – Luke Jun 13 '12 at 06:24
  • Yes, you can do that. But I don't use quotes, so it goes just like this: `[@security.context]`. – Elnur Abdurrakhimov Jun 13 '12 at 13:31