Skip to content

Instantly share code, notes, and snippets.

@andriesss
Last active December 10, 2015 15:08
Show Gist options
  • Save andriesss/4452477 to your computer and use it in GitHub Desktop.
Save andriesss/4452477 to your computer and use it in GitHub Desktop.
<?php
namespace Stca\Form\Element;
class RenderViewScript extends \Zend_Form_Element
{
/**
* File name of view script
* @var string
*/
protected $viewScript;
/**
* Sets filename of the view script to render
*
* @param $viewScript
* @return RenderViewScript
*/
public function setViewScript($viewScript)
{
$this->viewScript = $viewScript;
return $this;
}
/**
* Returns filename of view script to render
*
* @return mixed
*/
public function getViewScript()
{
return $this->viewScript;
}
public function render(\Zend_View_Interface $view = null)
{
if (null === $view) {
/** @var $viewRenderer \Zend_Controller_Action_Helper_ViewRenderer */
$viewRenderer = \Zend_Controller_Action_HelperBroker::getStaticHelper('viewRenderer');
if (null === $viewRenderer->view) {
$viewRenderer->initView();
}
$view = $viewRenderer->view;
}
return $view->render($this->getViewScript());
}
}
// usage
use Stca\Form\Element\RenderViewScript;
$form->addElement(new RenderViewScript('name', array('viewScript' => 'some/script.phtml')));
@robertbasic
Copy link

I usually do this the other way round:

<?php
class MyForm extends Zend_Form {
    public function render(Zend_View_Interface $view=null) {
        return $this->getView()->partial('_myform.phtml', array('form' => $this));
    }
}

Needs bit work to make the _myform.phtml view script, but this is what I found to be the most flexible/powerful way to work with complicated forms.

@andriesss
Copy link
Author

Right, but in that case you need list all elements of your form in the view script. I created this as a solution to inject custom HTML in the form.

@david4worx
Copy link

There is no need to list form elements, a foreach is also an option. That way there is no need to know what's in the form as it should really matter when rendering it.

Depending on the complexity of the crap inside your form (it should only contain elements and form semantic elements!) the solution by @andriesss is certainly viable.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment