0
votes

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...?

1

1 Answers

1
votes

Simple answer: no you can't. Elements can also be a part of a fieldset so they're not directly coupled to a form element.

You could take a different approach with your viewhelper. As in: $myHelper::__invoke(Form $form) or $myHelper::setForm(Form $form), which sets the form. From within that method you can check whether or not the form $form::hasValidated() because that tells us that the form was posted. Then from with the $myHelper::render(ElementInterface $element), you could add some logic to add the wrapperclass as in your example. And within your example merge the classes so that the wrapper doesnt replaces all the form element (css) classes.