简体   繁体   English

Zend 2-每页表格

[英]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: 当然,您可以在表单中应用任何登录名,无论您需要重用什么:

  1. Return a form instance so your view can render the form 返回一个表单实例,以便您的视图可以呈现该表单
  2. Return a rendered view already in the helper so your view does not need to render 返回帮助器中已经存在的渲染视图,因此您的视图不需要渲染
  3. Set all kind of options to the form 设置表格的所有选项
  4. Etc 等等

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM