I have a base User form that I am subclassing for each use case, i.e. Register, Edit, etc.
Some form elements are common to all use cases and for these I am using the form as an element factory, e.g. $this->addElement(‘text’, ‘first_name’, array(…)). That works fine.
For elements which are required in only some use cases, I am creating them in the base form class, but not adding them, e.g. $this->createElement(‘text’, ‘id’, array(…)). When I get to the subclass itself, that’s when I actually add these optional elements.
Now, I thought that in the subclass I would be able to simply add the element using either:
$this->addElement($this->getElement('id'));
Or
$this->addElement($this->id);
But that’s not the case. I get an exception saying I am trying to addElement(NULL).
The only way I can get the desired result is to specifically assign the create element to a member variable, then later use that variable name.
e.g. In the base form:
$this->id = $this->createElement('text', 'id', array(...));
Then in the sub class:
$this->addElement($this->id);
It seems to me that this should produce a variable name clash. If createElement is not naming my element ‘id’, what is it naming it?
EDIT
I am using the init() methods in both parent and child classes, and the child’s init() calls parent init() as its first task.
createElementdoes not add an element to the form, it just creates it. Unless you add it to your form, the form will not know about it. That’s why$this->idand$this->getElement('id')don’t work in your first example.In your second example, you first add the newly created element to the form (i.e.
$this->id = $this->createElement('text', 'id', array(...));) and then it seems you are adding it again (i.e.$this->addElement($this->id);). I believe that there won’t be any name clash, as Zend_Form will just reassign it. Thus I think$this->addElement($this->id);is in fact not needed.Hope this helps.