我是Zend2的新人:
我有一个表单,在第一阶段,我创建了一个新的ViewModel并返回它:
return new ViewModel(array('form' => $form, 'messages' => $messages));
在后期阶段,当数据从浏览器回来,我怎么能把这个相同的表单连接到一个新的视图(其中有相同的元素可能更少,也许更多)或创建另一个表单,并重新分配它的旧表单的数据,并将其关联到一个新的视图显示?
如有任何帮助,不胜感激。
编辑:我试着做以下事情:
形式-> setAttribute(‘行动’,$ this -> url(身份验证/索引/login-post.phtml));
但仍然显示旧的。
当我这样做时:
返回$ this ->重定向()-> toRoute(身份验证/违约,数组("控制器"=>"索引",'行动' => ' login-post '));
我得到错误页面:请求的控制器无法调度请求。
当我得到请求的帖子,我需要加载另一个视图,我的意思是我如何指定哪个视图连接到哪个表单?
表单本身并不了解视图。如果您希望在完成表格提交后更改视图;这个新视图可能提供了一个不同的表单,这是应该在控制器中完成的事情。
一个(不工作的)示例,其中有一些关于如何返回不同视图的选项。
class FooController extends AbstractActionController
{
public function getFooForm()
{
return $this->getServiceLocator()->get('Form'Foo');
}
public function getBarForm()
{
return $this->getServiceLocator()->get('Form'Bar')
}
public function fooAction()
{
$request = $this->getRequest();
$form = $this->getFooForm();
if ($request->isPost()) {
$form->setData($request->getPost());
// Is the posted form vaild
if ($form->isValid()) {
// Forms validated data
$data = $form->getData();
// Now there are a few options
// 1. Return a new view with the data
$view = new ViewModel($data);
$view->setTemplate('path/to/file');
return $view;
// OR Option 2 - Redirect
return $this->redirect()->toRoute('bar', $someRouteParams);
// Option 3 - Dispatch a new controller action
// and then return it's view model/response
// We can also pass on the posted data so the controller
// action that is dispathed will already have our POSTed data in the
// request
$request->setPost(new 'Zend'Stdlib'Parameters($data));
return $this->forward()->dispatch('App'Controller'Foo', array('action' => 'bar'));
}
}
// Render default foo.phtml or use $view->setTemplate('path/to/view')
// and render the form, which will post back to itself (fooAction)
return new ViewModel(array('form' => $form));
}
public function barAction()
{
$request = $this->getRequest();
$form = $this->getBarForm();
if ($request->isPost()) {
$form->setData($request->getPost());
// ....
}
// Renders the bar.phtml view
return $this->viewModel(array('form' => $form));
}
}
根据我对你的问题的理解,你需要使用选项3,因为新视图应该用它已经验证的数据填充第二个表单。
如果你指的是编辑视图之类的东西,那么你只需要将对象绑定到表单。
$form->bind($yourObject);
http://zf2.readthedocs.org/en/latest/modules/zend.form.quick-start.html将对象绑定
否则,你可以通过设置:
$form->setAttribute('action', $this->url('contact/process'));
可以把你的代码和更多的细节贴出来,我相信你会得到一些更详细的答案