How to Get sfContext in Symfony 1.4 form – Inject Your Dependency!

This is very unuseful to not having access to sfContext in the Symfony 1.4 forms for many reasons, for example to check whether user logged in or not or check user credentials and show/hide form widgets/validators.

As far as we all know that Why sfContext::getInstance() Is Bad we need some workaround.

The best way is to pass context object into form from action/component (aka “Dependency Injection”), like here:

and in the form do thing like this:

Apart from this you can create smart getters & setters to not forget to pass context to form:

And, finally, you can add this to the superclass of your all forms in your project.