Add HTML placeholder into Zend_Form

2019-05-20 06:16发布

问题:

I'm using Zend_Form for an application form using this code:

class Form_ApplicationForm extends Zend_Form
{
    public function init()
    {
        $this->setAction('/application/new')
             ->setMethod('post')
             ->setAttrib('id','application');

        $name = new Zend_Form_Element_Text('name');
        $name->setLabel('Your Name')
             ->setRequired(TRUE)
             ->addValidator('alpha', FALSE, array('allowWhiteSpace' => true));

        $email = new Zend_Form_Element_Text('email');
        $email->setLabel('Email Address')
              ->setRequired(TRUE)
              ->addValidator('EmailAddress');

        $this->addElements(array($name,$email));
    }
}

I'm adding a flash file uploader (swfupload) to this form which needs a HTML snippet to be in place to work, the snippet looks like this:

<div id="swfupload-control">
    <p>Upload upto 5 image files(jpg, png, gif), each having maximum size of 1MB(Use Ctrl/Shift to select multiple files)</p>
    <input type="button" id="button" />
    <p id="queuestatus" ></p>
    <ol id="log"></ol>
</div>

What is the best way of inserting this so that it sits somewhere within the <form> which i'm inserting within my controller like this:

public function newAction()
{
    $form = new Form_ApplicationForm();
    if($this->_request->isPost()){
        $data = $_POST;
        if($form->isValid($data)){
            /// handle data here
        }else{
            $form->populate($data);
        }
    }
    $this->view->form = $form;
}

Is there a way of adding a placeholder or similar within Zend_Form, or should this be done using a decorator or something like that?

Thanks.

回答1:

You'd have to write your own Element for this, e.g. My_Form_Element_SwfUpload along with a renderer. See these tutorials:

  • The simplest Zend Form Decorator
  • How to layer Decorators
  • Rendering Zend Form Decorators individually
  • Creating composite elements


回答2:

The simplest way is to do it in the view:

By echoing each element you can print its html. Here's one way to do it:

<form id="<?= $this->form->getId() ?>" action="<?= $this->form->getAction() ?>">

<? foreach ($this->form as $element): ?>
<?= $element ?>
<? if ($element->getName() == 'email'): ?>
<div id="swfupload-control">
    <p>Upload upto 5 image files(jpg, png, gif), each having maximum size of 1MB(Use Ctrl/Shift to select multiple files)</p>
    <input type="button" id="button" />
    <p id="queuestatus" ></p>
    <ol id="log"></ol>
</div>
<? endif ?>
<? endforeach ?>

</form>

What this does is it prints all the elements, and puts whatever you have to after the email field. If you add or remove a field from the form this code will continue to work (of course it will fail if you remove the email field).