phpzend-framework2overridingextending-classes

ZF2 change extends class


The answer to my question ZF2 FormInput to show error class on validation fail is to create my own form view helper, overriding the render function. While this works beautifully for elements being rendered using forminput, it doesn't help on elements that inherit from forminput. For example, FormCheckbox inherits from forminput but not MY forminput:

<?php
namespace Zend\Form\View\Helper;
//...
class FormCheckbox extends FormInput {
    //...
}

In this case I would need to create ANOTHER form view helper for formcheckbox exclusively to extend MY forminput. And again for any other view helpers I want to include (formdate, formemail, formpassword, etc).

Instead of creating multiple view helpers is it possible to create a single view helper and tell ZF2 to use that in all calls to the original view helper when made by a ZF2 view helper?

i.e. \Zend\Form\View\Helper\FormCheckbox would extend \RPK\Form\View\Helper\FormInput, which would extend \Zend\Form\View\Helper\FormInput.


Solution

  • I am using composer to install ZF2. As composer is generating my autoload functions I can specify an autoload path in the composer.json file:

    "autoload": {
        "psr-4": {
            "Zend\\Form\\View\\Helper\\": "vendor/rpk/Rpk/Form/View/Helper"
        }
    },
    

    This will search in my vendor folder for the class before looking in the zend folder.

    This does not let me extend the FormInput, but calls my FormInput in its place. Calling extends on my FormInput puts the app into an infinite loop, so we need to copy the contents of FormInput into my class and make the changes there.