Skip to content
This repository has been archived by the owner on Jan 30, 2020. It is now read-only.

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

Open
Erikvv opened this issue Aug 20, 2018 · 1 comment

Comments

@Erikvv
Copy link
Contributor

Erikvv commented Aug 20, 2018

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

This is closely related to #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).

@Erikvv Erikvv changed the title Element::init is called before Element::setOptions when using Zend\Form\Factory Element::init is called before Element::setOptions when using Zend\Form\Factory but not when using FormElementManager Aug 20, 2018
@weierophinney
Copy link
Member

This repository has been closed and moved to laminas/laminas-form; a new issue has been opened at laminas/laminas-form#3.

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

No branches or pull requests

2 participants