Created
November 19, 2012 21:16
-
-
Save leup/4113974 to your computer and use it in GitHub Desktop.
Custom Form Elements and View Helpers for Zend Framework 2
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace Admin\Form\View\Helper; | |
use Zend\Form\ElementInterface; | |
use Zend\Form\View\Helper\FormElement; | |
class ExFormElement extends FormElement | |
{ | |
/** | |
* Overrides method to render an element. | |
* | |
* Uses a custom view helper if defined by element. | |
* Else, go back to parent render method. | |
* | |
* @param ElementInterface $element | |
* @return string | |
*/ | |
public function render(ElementInterface $element) | |
{ | |
if ($element instanceof ExFormElementInterface) { | |
$renderer = $this->getView(); | |
if (!method_exists($renderer, 'plugin')) { | |
// Bail early if renderer is not pluggable | |
return ''; | |
} | |
$helper = $renderer->plugin( $element->getViewHelperName() ); | |
return $helper($element); | |
} | |
return parent::render($element); | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace Admin\Form\View\Helper; | |
interface ExFormElementInterface | |
{ | |
public function getViewHelperName(); | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// ... // | |
public function getViewHelperConfig() | |
{ | |
return array( | |
'factories' => array( | |
'exFormElement' => function($sm) { | |
$helper = new ExFormElement; | |
return $helper; | |
}, | |
'Admin\Form\View\Helper\FormFile' => function($sm) { | |
$helper = new \Admin\Form\View\Helper\FormFile; | |
return $helper; | |
} | |
) | |
); | |
} | |
// ... // |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment