I am developing a custom field for the Forms Component in Silex. The purpose of this field is to render and validate a captcha image/value.
I was able to add a FormExtension that registers my custom type.
I am injecting the $app['session'] to be able to store the captcha value in the session. Everything seems to work as expected until I start on touching the session.
Here’s the error I get:
Failed to start the session because headers have already been sent.
Hereunder is how I register my FormExtension and how it instanciates the custom field type:
$app->register(new FormServiceProvider());
$app['form.extensions'] = $app->share(
$app->extend('form.extensions', function ($extensions) use ($app) {
$extensions[] = new CaptchaFormExtension($app['captcha.options'], $app['session']);
return $extensions;
})
);
class CaptchaFormExtension extends AbstractExtension
{
private $session;
private $options;
public function __construct($options = array(), Session $session)
{
$this->options = $options;
$this->session = $session;
}
protected function loadTypes()
{
return array(
new CaptchaType($this->options, $this->session)
);
}
}
So I have figured out what the problem was.
The error message was actually pretty much self-explanatory.
Actually I don’t use the session prior to the calls in the
CaptchaTypeso it only gets started at that point, which is, as the error message says, too late.Solution I have came up with is to explicitly start the session at the beginning of my controller action. I can then use the session inside the custom form type as I want to.