views:

22

answers:

2

Is there some method that accepts inserting custom html without having to actually add form controls, even if they're hidden and making my html a decorator?

I'm looking for something like:

$this->addCustomElement( array(
'div', 
'body' => '<p>inner text</p>'
) );

I need something short and quick, I don't want to create a new class or something overkill.

+2  A: 

Well it's really as simple as this:

$note = new Zend_Form_Element('note');
$note->helper = 'formNote';
$note->setValue('<b>hi</b>');
$form->addElement($note);

But the problem is that when you submit the form, the form calls $note->isValid(), which overrides the value, so if there are errors with the form, the next time you display it, the custom HTML won't be shown. There are two easy ways to fix this, the first is to override isValid() in your Form class like this:

public function isValid($data)
{
    $note = $this->note->getValue();
    $valid = parent::isValid($data);
    $this->note->setValue($note);
    return $valid;
}

But personally I find this kinda hackish way, and prefer the second option. That is to write a very simple class (this should really be part of Zend itself, I have no idea why it isn't, since it includes a formNote view helper, but no element that uses it):

class My_Form_Element_Note extends Zend_Form_Element_Xhtml
{
    public $helper = 'formNote';
    public function isValid($value, $context = null) { return true; }
}

Then you just have to do:

$note = new My_Form_Element_Note('note');
$note->setValue('<b>hi</b>');
$form->addElement($note);

And everything will just work.

Other options include doing some black magic with decorators, but I really recommend you to not go down that path.

reko_t
Awesome. I haven't done Zend in awhile though, where would one define this class, directory-structure-wise and file-name-wise?
meder
I usually store classes like this under `library/App/`, so in my case the class would be called `App_Form_Element_Note`, and it'd reside in `library/App/Form/Element/Note.php`
reko_t
+2  A: 

Also note the AnyMarkup Decorator.

David Weinraub