Question: Is it possible to access to the Form class from an added element?
Example case:
Note: This example makes no sense as it is, but that's not exactly what I'm trying to do: It's just to keep things simple
Suppose to have a custom view helper that wraps an element into a div. Something like:
public function render(ElementInterface $element = NULL) {
return '<div class="myclass">'.$this->view->formElement($element).'<div>';
}
I would like to retrive the class 'myclass' from the element itself and add it to the div only if the form has been submitted. Something like:
public function render(ElementInterface $element = NULL) {
$class='default';
if(isset($_POST['submit'])){
$class=$element->getOption('wrapper_class');
}
return'<div class="'.$class.'">'.$this->view->formElement($element).'<div>';
}
That works (if 'submit' is the name of the submit button) but, if I have two forms into the same page the second form submission will trigger the above condition and the class will be applied.
A workaround could be:
class MyForm extends Form {
public function __construct($name = null){
parent::__construct($name);
$this->add([
'name' => 'myElement',
'type' => MyCustomElement::class,
'options' => [
'triggered_by' => $this->getName(),
'wrapper_class'=>'myClass',
],
]);
$this->add([
'name' => $this->getName(),
'type' => 'submit',
'attributes' => [
'value' => 'Go',
'id' => 'submitbutton',
'class'=>'btn btn-success',
],
]);
}
}
and then: if(isset($_POST[$element->getOption('triggered_by')])){ ... }
But that works good only if the custom element is added directly to the form. If it's added to a fieldset then $this->getName() will return the name of the fieldset. Obviously the name could be added as a string but I would like to avoid it (typos).
The top solution would be to have access to the main form's options/attributes from all the sub-elements but the elements do not extend Form (myElement->extend Element , Form->extend Fieldset->extend Element).
...then...?