简体   繁体   中英

Zend Framework/Form Elements: Create custom class or?

the result i want is a textarea that hooks up to WMD (markdown editor). and include a div.wmd-preview element. what i have currently is in my forms (extending Zend_Form ) ... i add the functionality thru decorators

// init()
$this->addElement('textarea', 'bio', array(
    'label' => 'Bio',
    'description' => '<a href="http://daringfireball.net/projects/markdown/syntax" target="_blank" title="get markdown editing/syntax help">Markdown enabled</a>',
    'validators' => array(
        array('StringLength', false, array(0, 1000))
    ),
    'decorators' => array(
        'ViewHelper',
        'Errors',
        array('Description', array('tag' => 'p', 'escape' => false)),
        'Label',
        array('HtmlTag', array('tag' => 'p')),
        new Application_Form_Decorator_WmdPreview,
     )
));
...
// add WMD & Prettify
$bootstrap = Zend_Controller_Front::getInstance()->getParam('bootstrap');
$view = $bootstrap->getResource('view');
$view->headScript()->prependFile($view->baseUrl("/js/wmd/wmd.js"))
                   ->prependScript('wmd_options = {"output": "Markdown"};')
                   ->prependFile($view->baseUrl("/js/prettify/prettify.js"));
$view->headLink()->prependStylesheet($view->baseUrl('/js/prettify/prettify.css'));
}

but if i want most textareas to be wmd-enabled, i think it might be better to encapsulate all these in a separate class? or somekind of wrapping element? either way, it will be nicer if i can do something like

$this->addElement(new Application_Form_Element_WmdEditor); 

or something similar

if the answer is to create a custom Zend_Form_Element , how do i go abt doing it? just create a custom view helper that contain all that markup? what if i want other decorators like errors and description to be put inbetween the textarea and the preview div?

Create a new form element class that extends Zend_Form_Element_TextArea:

final class Application_Form_Element_WmdEditor extends Zend_Form_Element_TextArea {
    public $helper = 'WMDEditor';
}

And then like you say a view helper:

final class Application_View_Helper_WMDEditor extends Zend_View_Helper_FormElement {

     public function WMDEditor($name, $value = null, $attribs = null) {
        //set it up here
     }
}

This way you also have all the advantages of the standard form element helpers

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM