[英]Zend 2 - Form on every page
I am new to Zend Framework 2 我是Zend Framework 2的新手
I want to add a form to every page (a login box for example) that functions as it does when in its own module ie. 我想向每个页面(例如,一个登录框)添加一个表单,该表单在其自身的模块中即发挥作用。 so it validates and there is no need to redirect back from the module after the action.
因此它可以验证,并且在操作后无需从模块重定向回去。
I have looked at various things such as view helpers and action helpers, I have not posted any code as it may just add confusion 我看过各种东西,例如视图助手和动作助手,我没有发布任何代码,因为它可能只会增加混乱
I am looking for a guide on how to achieve this as I currently am confused as to how this would be best implemented 我正在寻找有关如何实现此目标的指南,因为目前我对如何最好地实现该目标感到困惑
This is certainly a use case for a view helper. 这当然是视图助手的用例。 This provides a piece of logic reusable in multiple views across different modules.
这提供了可在不同模块之间的多个视图中重用的逻辑。
Take for example the login form,. 以登录表单为例。 you might want to return a
Zend\\Form\\Form
instance when you call the helper. 您可能需要在调用帮助程序时返回
Zend\\Form\\Form
实例。 So first, create the helper: 因此,首先创建助手:
namespace MyLogin\View\Helper;
use Zend\View\Helper\AbstractHelper;
use Zend\Form\Form;
class LoginForm extends AbstractHelper
{
public function __invoke()
{
$form = new Form;
$url = $this->getView()->url('user/login');
$form->setAttribute('action', $url);
$form->add([
'name' => 'username',
]);
$form->add([
'type' => 'password',
'name' => 'password',
]);
return $form;
}
}
Then you register this view helper under the name "loginForm" in your config: 然后,在配置中以名称“ loginForm”注册此视图帮助器:
'view_helpers' => [
'invokables' => [
'loginForm' => 'MyLogin\View\Helper\LoginForm',
],
],
Now you can use the helper in your views: 现在,您可以在视图中使用该帮助器:
<?php $form = $this->loginForm() ?>
<?= $this->form()->openTag($form)?>
<?= $this->formRow($form->get('username'))?>
<?= $this->formRow($form->get('password'))?>
<button type="submit" value="Login">
<?= $this->form()->closeTag()?>
Of course you can apply any login in your form, whatever you need to be reusable: 当然,您可以在表单中应用任何登录名,无论您需要重用什么:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.