Have run into a curious behavior a few times over the years, have always meant to ask about it.
It has to do with a behavior I don't understand around binding objects to forms in Zend Framework.
Consider this factory which builds a form, loads a Doctrine entity from database, and attempts to bind it to the form (so that the values display on render):
class TermsConfigFormFactory implements FactoryInterface
{
public function __invoke(ContainerInterface $container, $requestedName, array $options = null)
{
$form = new TermsConfigForm('terms_config_form', $options);
$form->setInputFilter($container->get('InputFilterManager')->get(TermsConfigInputFilter::class, $options));
$form->setHydrator(new DoctrineHydrator($container->get('doctrine.entitymanager.orm_default'), false));
if (!is_string($options['locale'])) {
throw new \InvalidArgumentException("An illegal locale variable was received by the terms configuration factory");
}
$termsConfig = $container->get(TermsConfigMapper::class)->get($options['locale']);
if (!$termsConfig) {
$termsConfig = new TermsConfig($options['locale']);
}
// A. If we do just this, the form doesn't print data
$form->bind($termsConfig);
return $form;
}
}
The form is well wired through form_elements, and so forth. We then attempt to use it inside a Controller like so:
$termsForm = $this->formElementManager->get(TermsConfigForm::class, ['locale' => $this->locale()]);
$viewModel->setVariable('termsForm', $termsForm);
Interestingly, we find that the object will not show the bound data in the ViewModel. Now, even more curious, is if we remove the call to "bind" in the factory and do this in the controller instead, the values are properly displayed!!
$termsForm = $this->formElementManager->get(TermsConfigForm::class, ['locale' => $this->locale()]);
// B. You have to do this in the controller, here, for it to print data!
$termsForm->bind($termsForm->getObject());
$viewModel->setVariable('termsForm', $termsForm);
Why does it not work within the factory?
From this vantage point, the call to bind in the controller, is analogous to the call to bind in the Factory. I'd like to keep this stuff in the factory, but seems I cannot!