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:

class marketComponents extends sfComponents
{

    public function executeActionName()
    {
        // offer
        $this->form = new ourBeautifulForm(null, array('context' => $this->getContext()));
    }
}

and in the form do thing like this:

class ourBeautifulForm extends sfForm
{
    private $sfContext = null;

    public function configure()
    {
        $this->sfContext = $this->getOption("context");
    }
}

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

    public function getContext()
    {
        if (!$this->sfContext) {
            $sfContext = $this->getOption("context");

            if ($sfContext instanceof sfContext) {
                $this->setContext($this->getOption("context"));
            } else {
                throw new InvalidArgumentException('Please pass sfContext dependency to the form ' . get_class($this));
            }
        }

        return $this->sfContext;
    }

    /**
     * @param null $sfContext
     */
    public function setContext($sfContext)
    {
        $this->sfContext = $sfContext;
    }

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