如何在Zend表单中添加“纯文本节点”?

19

我想在Zend表单中添加一个纯文本节点,目的是仅显示一些静态文本。

问题在于 - 我不知道有任何可以这样做的方法。

我已经使用了“description”,但那必须附加到一个表单元素上。

有没有简单地将一些文本作为表单的一部分显示的方法?Zend将所有内容视为表单元素,因此我不能只打印出来。

例如:

以下将测试您对某事物的能力。 . . .

等等...

有什么想法吗?


我认为最佳答案是Aine的。 - Emilio Nicolás
7个回答

37

Zend提供了一个表单注释视图助手(Zend_View_Helper_FormNote),您可以使用它来添加文本。

只需创建一个新的表单元素(/application/forms/Element/Note.php):

class Application_Form_Element_Note extends Zend_Form_Element_Xhtml  
{  
    public $helper = 'formNote';  
}

在你的表单中:

$note = new Application_Form_Element_Note(
    'test',
    array('value' => 'This is a <b>test</b>')
);
$this->addElement($note);

11
请在这个类中添加以下函数:`public function isValid($value){ return true; }`这样,在验证过程中,该元素就不会消失了。 - juque
1
我认为根据这个解决方案的声誉和简单性,这应该是正确的答案 :) - John Skoumbourdis
1
我尝试了这个和一堆相关的方法,但都没能让它们正常工作。然而,https://dev59.com/F3E95IYBdhLWcg3wRL0t#15908841 对我有用。 - Ryan

10

添加一个带有非转义描述的隐藏元素即可。

$form->addElement('hidden', 'plaintext', array(
    'description' => 'Hello world! <a href="#">Check it out</a>',
    'ignore' => true,
    'decorators' => array(
        array('Description', array('escape'=>false, 'tag'=>'')),
    ),
));

完美运作。它仍然附加在一个元素上,但是不会以这种方式呈现。

代码来自:http://paveldubinin.com/2011/04/7-quick-tips-on-zend-form/


8
这就是为什么我喜欢Zend。不,其实并不是。 - Oiva Eskola
对我来说,这是最好的答案,因为当表单被POST时,formNote(helper)元素会消失。 - Ramon Fincken

6

可能有更好的方法,但我通过使用自定义表单元素和视图助手创建了一个段落。对于这么简单的东西来说,似乎需要很多代码。如果您找到了更简单的方法,请告诉我。

//From your form, add the MyParagraph element
$this->addElement(new Zend_Form_Element_MyParagraph('myParagraph'));

class Zend_Form_Element_MyParagraph extends Zend_Form_Element
{
    public $helper = 'myParagraph';
    public function init()
    {
        $view = $this->getView();
    }
}

class Zend_View_Helper_MyParagraph extends Zend_View_Helper_FormElement {

    public function init() {
    }

    public function myParagraph() {
        $html = '<p>hello world</p>';
        return $html;
    }

}

6

有点晚了,但我仍然希望为社区做出贡献。

Aine说得一点不错。如果您想在Zend_Form中使用文本,则需要使用FormNote。但是,您可以在不需要扩展Zend_Form_Element_Xhtml的情况下使用它。请参见以下示例:

$text = new Zend_Form_Element_Text('myformnote');
$text->setValue("Text goes here")
     ->helper = 'formNote';

请注意,您可以在formNote助手中使用文本和HTML。

谢谢。这是唯一有效的方法。 - Ryan
这个代码是有效的,但当你验证表单时元素会消失,这可能不是你想要的结果。请参阅上面axiom82的回答以获得解决方案。 - Countzero

5
这个功能可以通过Zend_Form_Element_Note在Zend中实现。
$note = new Zend_Form_Element_Note('forgot_password');
$note->setValue('<a href="' . $this->getView()->serverUrl($this->getView()->url(array('action' => 'forgot-password'))) . '">Forgot Password?</a>');

这是正确的答案。没有必要无用地扩展它,并像最受欢迎的答案中所做的那样覆盖$helper与相同的值。 - danronmoon
是的,比其他答案更优雅和简单。完美地工作并避免了验证时的消失。 - Countzero

3

我遇到了同样的问题,并决定不再使用Zend_Form,而是直接使用视图帮助程序(就像Ruby on Rails一样),并在模型上进行验证。


0
这个一行代码对我很有效:
$objectForm->addElement(new Zend_Form_Element_Note('note', array('value' => 'Hello World')));

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接