Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Element::init is called before Element::setOptions when using Zend\Form\Factory but not when using FormElementManager #3

Open
weierophinney opened this issue Dec 31, 2019 · 0 comments

Comments

@weierophinney
Copy link
Member

How can you initialize if you don't have the options?

This is closely related to zendframework/zend-form#138

Code to reproduce the issue

use Zend\Form\Factory;
use Zend\Form\Element;
use Zend\Form\FormElementManager\FormElementManagerV3Polyfill;
use Zend\ServiceManager\ServiceManager;

class MyElement extends Element
{
    public function init()
    {
        echo "init\n";
    }

    public function setOptions($options)
    {
        echo "setOptions\n"
    }
}

// scenario 1, incorrect
// same as calling $this->add() inside a fieldset
$factory = new Factory();
$factory->create([
    'type' => MyElement::class,
    'options' => [
        'my_option' => true
    ]
]);

echo "\n";

// scenario 2, correct
$formElementManager = new FormElementManagerV3Polyfill(new ServiceManager());
$countrySelect = $formElementManager->get(MyElement::class, [
    'my_option' => true
]);

Expected results

setOptions
init

setOptions
init

Actual results

init
setOptions

setOptions
init

Workaround

There are several different workarounds:

  • Don't use Zend\Form\Factory. This means don't use $this->add() in a fieldset. Write factories which initialize elements and fieldsets.
  • Manually call ->init() again on the element after it's been created
  • Implement ElementPrepareAwareInterface instead of InitializableInterface (adds an unused dependency from Element to Fieldset)
  • Apply the 1-line fix to Zend\Form\Factory:
- $element = $this->getFormElementManager()->get($type);
+ $element = $this->getFormElementManager()->get($type, $spec['options'] ?? []);

Proper fix

I don't see a coherent solution which doesn't involve overhauling how stuff works.

If you move towards constructor injection this would break many factories people wrote.

Zend\ServiceManager\Initializer\InitializerInterface does not support passing options. If it did you could move the setOptions() logic to there with little BC break.

(DelgatorFactoryInterface does support passing options but you'd have to register it for every element).


Originally posted by @Erikvv at zendframework/zend-form#221

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant