我们如何在视图中呈现表单元素,该表格元素是从控制器动态添加的?
答案 0 :(得分:0)
我认为你想要这样的事情
在您的控制器中:
use Publicacion\Form\AlbumForm;
use Zend\Form\Element;
class ControllerAlbum extends AbstractActionController
{
// example action
public function addAction(){
$album=new Album();
$form=new AlbumForm();
// create element username
$username = new Element\Text('username');
$username
->setLabel('Username')
->setAttributes(array('class' => 'username','size' => '30',
));
// create element password
$password = new Element\Password('password');
$password
->setLabel('Password')
->setAttributes(array('size' => '30',
));
$form->add($username);
$form->add($password);
$form->bind($album);
$request=$this->request->getRequest();
if($request->isPost()){
//... doing anything
return $this->redirect()->toRoute('album');
}
return new ViewModel(array('form' => $form));
}
}
班级专辑形式:
//示例类
use Zend\Form\Form;
class AlbumForm extends Form
{
public function __construct($name = null)
{
// we want to ignore the name passed
parent::__construct('album');
$this->add(array(
'name' => 'id',
'type' => 'Hidden',
));
$this->add(array(
'name' => 'title',
'type' => 'Text',
'options' => array(
'label' => 'Title',
),
));
$this->add(array(
'name' => 'artist',
'type' => 'Text',
'options' => array(
'label' => 'Artist',
),
));
$this->add(array(
'name' => 'submit',
'type' => 'Submit',
'attributes' => array(
'value' => 'Go',
'id' => 'submitbutton',
),
));
}
}
视图add.phtml
<?php
$form = $this->form;
$form->setAttribute('action', $this->url('post', array('action' => 'add')));
$form->prepare();
echo $this->form()->openTag($form);
echo $this->formHidden($form->get('id'));
echo $this->formRow($form->get('title'));
echo $this->formRow($form->get('artist'));
echo $this->formRow($form->get('username'));
echo $this->formRow($form->get('password'));
echo $this->formSubmit($form->get('send'));
echo $this->form()->closeTag();
?>
希望这可以帮到你