I am writing a more advanced file form element, more of a widget that displays the currently loaded uploaded image as well as validating image sizes etc.
If the file validates, I want the form element itself to copy the file to a publicly accessible folder. This will mean that a) the image can be displayed and b) if the whole form doesn’t validate, the user does not need to re-upload the image.
Anyway that’s the back story, but essentially I need to figure out how to get a function from within a form element to run when the form validates that element. Something like creating an onValidate() function in the form element class.
Most importantly I need a solution that doesn’t spill out into the controller (or as little as possible). I am struggling to find a clean way to implement this.
I would like to do something like this…
class File extends Element implements InputProviderInterface
{
....
public function isValid()
{
if ( $isValid = parent::isValid() ) {
echo "Hi there, glad you called";
}
return $isValid;
}
The
Zend\Form\Element::getValidator()function will be called on each validation run.I think you should call a class which’s concern it is to copy the file.
Maybe you want to raise an event to make it more decoupled.
Validation and Filtering are now part of the InputFilter class.
Your goal is to write an dedicated Validator and hardwire it with your Element.
An example of how to achieve this, look at Zend\Form\Element\Select which as a hardwired
InArrayValidatorin itsonValidate()method.