Adding a dollar sign to a text field in Zend Framework

孤街浪徒 提交于 2019-12-23 04:17:12

问题


Is there a way to add a "$" right before the <input> for a Zend_Form element? (using standard ZF stuff would be great, of course).

EDIT: For example, if the html generated by Zend_Form for a cost element is something like: (very simplified)

<label>Cost:</label>
<input type="text" name="cost" />

I'd like it to output this:

<label>Cost:</label>
$ <input type="text" name="cost" />

回答1:


You can use callback decorator to put whatever html you want in your elements:

For example in your case I could do:

    $el1 = $this->createElement('text', 'el1')->setLabel('Cost:');

    // Anonymous function that will generate your custom html (needs PHP 5.3).
    // For older PHP there are other ways of making anonymous functions.
    $myHtml = function($content, $element, array $options) {
                return '$';
            };
    $el1->setDecorators(array(
        'ViewHelper',
        'Errors',
        array('Callback', array('callback' => $myHtml, 'placement' => 'PREPEND')),
        'Label'
    ));

This should result in the following html code:

<label for="el1" class="optional">Cost:</label> 
$
<input type="text" name="el1" id="el1" value="" /> 

Hope this will be helfull or at least point you in the right direction.




回答2:


Using the AnyMarkup decorator, you could do something this:

$element->setDecorators(array(
    'ViewHelper',
    array('AnyMarkup', array('markup' => '$', 'placement' => 'prepend')),
    // And any other decorators, like Label, Description, Errors, and 
    // other wrapping like td, tr, etc.
));

As usual, be sure to register the namespace for the decorator with the form. So, if you use the class as named in the linked snippet My_Decorator_AnyMarkup located in the file My/Decorator/AnyMarkup.php on the include path, then you'd need something like:

$form->addElementPrefixPath('My_Decorator_', 'My/Decorator', 'decorator');




回答3:


You can add it as a description

$this->createElement('text', 'cost')
     ->setLabel('Cost:')
     ->setDescription('$');

And then configure element's decorators properly.

Upd:

Suggested element's decorators:

array(
    'ViewHelper',
    array('Description', array('placement' => Zend_Form_Decorator_Abstract::PREPEND, 'tag' => 'em'))
);

Note the placement option.



来源:https://stackoverflow.com/questions/5328529/adding-a-dollar-sign-to-a-text-field-in-zend-framework

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!