我在Zend表单中创建了以下元素:
// Add the submit button
$this->addElement('button', 'cancel', array(...)
));
按预期创建按钮元素。如果我想创建一个嵌套在其中的span标签的按钮元素,如下所示:
<button ...>
<span>Cancel</span>
</button>
有什么想法吗?
答案 0 :(得分:2)
另一个问题中答案的问题在于它使按钮可翻译功能无用。
这是我的解决方案。它实际上是Zend_Form_Element_Button
和Zend_View_Helper_FormButton
的副本,并增加了功能。
表单元素:
class App_Form_Element_ButtonPadded
extends Zend_Form_Element_Button
{
public $helper = 'formButtonPadded';
public function init()
{
$this->getView()->addHelperPath( 'App/View/Helper', 'App_View_Helper' );
}
}
视图帮助:
class App_View_Helper_FormButtonPadded
extends Zend_View_Helper_FormElement
{
public function formButtonPadded( $name, $value = null, $attribs = null )
{
$info = $this->_getInfo( $name, $value, $attribs );
extract( $info ); // name, id, value, attribs, options, listsep, disable, escape
// Get content
$content = '';
if( isset( $attribs[ 'content' ] ) )
{
$content = $attribs[ 'content' ];
unset( $attribs[ 'content' ] );
} else {
$content = $value;
}
// Ensure type is sane
$type = 'button';
if( isset( $attribs[ 'type' ] ) )
{
$attribs[ 'type' ] = strtolower( $attribs[ 'type' ] );
if( in_array( $attribs[ 'type' ], array( 'submit', 'reset', 'button' ) ) )
{
$type = $attribs[ 'type' ];
}
unset( $attribs[ 'type' ] );
}
// build the element
if( $disable )
{
$attribs[ 'disabled' ] = 'disabled';
}
$content = ( $escape ) ? $this->view->escape( $content ) : $content;
$xhtml = '<button'
. ' name="' . $this->view->escape( $name ) . '"'
. ' id="' . $this->view->escape( $id ) . '"'
. ' type="' . $type . '"';
// add a value if one is given
if( !empty( $value ) )
{
$xhtml .= ' value="' . $this->view->escape( $value ) . '"';
}
$paddingTag = 'span';
if( isset( $attribs[ 'paddingTag' ] ) )
{
$paddingTag = strtolower( (string) $attribs[ 'paddingTag' ] );
$paddingTag = strlen( $paddingTag ) ? $paddingTag : 'span';
unset( $attribs[ 'paddingTag' ] );
}
$paddingTagRepeat = 1;
if( isset( $attribs[ 'paddingTagRepeat' ] ) && $attribs[ 'paddingTagRepeat' ] >= 0 )
{
$paddingTagRepeat = (int) $attribs[ 'paddingTagRepeat' ];
unset( $attribs[ 'paddingTagRepeat' ] );
}
$paddingStartTag = '<' . $paddingTag . '>';
$paddingEndTag = '</' . $paddingTag . '>';
$content = str_repeat( $paddingStartTag, $paddingTagRepeat ) .
$content .
str_repeat( $paddingEndTag, $paddingTagRepeat );
// add attributes and close start tag
$xhtml .= $this->_htmlAttribs( $attribs ) . '>';
// add content and end tag
$xhtml .= $content . '</button>';
return $xhtml;
}
}
可能的用法:
$paddedButton = new App_Form_Element_ButtonPadded( array(
'type' => 'submit',
'label' => 'Your possibly translatable label',
'paddingTag' => 'span',
'paddingTagRepeat' => 2 // I've had to use double span's inside the button for my app
) );
欢迎改进。