4

Is there any way to inject container services into FormElement callbacks like '#process'? Or do I need to call \Drupal::container()->get(..)?

I noticed https://www.drupal.org/docs/8/api/services-and-dependency-injection/dependency-injection-for-a-form, but this is for forms, not for form element types.

2
  • 1
    All form element callbacks are simple callables so you would have to pass the whole instantiated object instead of just a class and method to call...and somehow instantiate it(maybe via wrapper?). In the end, it does not make any sense.
    – user21641
    Aug 7 '17 at 21:25
  • To clarify: I am not so interested whether it is technically called dependency injection, but if there is any clean way to use container services in a #process callback. It seems the answer is no.
    – donquixote
    Aug 8 '17 at 16:39
2

Dependency injection for any method of a class is done for the whole class. So if you have a dependency for the method you're adding for any method in the class, you will set that as a dependency for the whole class, not just a single function. However, #process callbacks are static functions, and static functions cannot use dependency injection. They should use the \Drupal::service() method, which is for static functions and procedural code.

3
  • see comment from @IvanJaros, the class is not instantiated and the callable is a static function, so you have no access to $this.
    – 4k4
    Aug 8 '17 at 6:39
  • If the callable is a static function, then there is no dependency injection. Dependency injection is only for non-static methods.
    – Jaypan
    Aug 8 '17 at 6:40
  • the downvote was not from me, the answer is not wrong. If you add the comment to the answer, it is clearer, that you mean, no, you can't use dependency injection for the static #process callback.
    – 4k4
    Aug 8 '17 at 6:52

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.