我是Zend2的新人:
我有一个表单,在第一阶段我创建一个新的ViewModel并返回它:
return new ViewModel(array('form' => $form, 'messages' => $messages));
在数据从浏览器返回的后期阶段,如何将此相同的表单连接到新的View(具有相同的元素可能更少,可能更多)或创建另一个表单并将其格式化为旧表单的数据并将它与一个新的观点联系起来?
任何帮助都将不胜感激。
编辑:
我尝试执行以下操作:
$ form-> setAttribute('action',$ this-> url('auth / index / login-post.phtml'));
但仍然显示旧的。
当我这样做时:
返回$ this-&gt; redirect() - &gt; toRoute('auth / default',array('controller'=&gt;'index','action'=&gt;'login-post')); < / p>
我收到错误页面:请求的控制器无法分派请求。
当我收到请求的帖子时,我需要加载另一个视图,我的意思是如何指定哪个视图连接到哪个表单?
答案 0 :(得分:0)
如果您指的是编辑视图之类的内容,则只需将对象绑定到表单即可。
$form->bind($yourObject);
http://zf2.readthedocs.org/en/latest/modules/zend.form.quick-start.html#binding-an-object
否则,您可以通过设置将表单发布到任何控制器操作:
$form->setAttribute('action', $this->url('contact/process'));
也许发布您拥有的代码和更具体的内容,我相信您会得到更详细的答案
答案 1 :(得分:0)
表格本身并不了解视图。如果您希望在完成表单提交后更改视图;这个新视图可能提供了不同的形式,这应该在控制器内完成。
一个(非工作)示例,其中包含有关如何返回不同视图的一些选项。
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 ,因为新视图应使用已经验证的数据填充第二个表单。