简体   繁体   中英

ZF2: Form in view helper

I've created a view helper to be used as a sidebar widget for newsletter subscription. Following the official zf2 tutorial for creating forms, i've added used the addAction's code inside __invoke()..

namespace Application\View\Helper;

use Zend\View\Helper\AbstractHelper;
use Application\Model\NewsletterTable;
use Application\Form\NewsletterForm;


class Newsletter extends AbstractHelper
{ 
    protected $newsletterTable;

    public function __construct(NewsletterTable $newsletterTable)
    {
        $this->newsletterTable = $newsletterTable;
    }

    public function __invoke()
    {      
        $form = new NewsletterForm();
        $form->get('submit')->setValue('Subscribe');

        $request = $this->getRequest();
        if ($request->isPost()) {
            $newsletter = new Newsletter();
            $form->setInputFilter($newsletter->getInputFilter());
            $form->setData($request->getPost());

            if ($form->isValid()) {
                $newsletter->exchangeArray($form->getData());
                $this->getNewsletterTable()->saveEmail($newsletter);
            }
        }

        return array('form' => $form);            
    } 

    public function getNewsletterTable()
    {
        if (!$this->newsletterTable) {
            $sm = $this->getServiceLocator();
            $this->newsletterTable = $sm->get('Application\Model\NewsletterTable');
        }
        return $this->newsletterTable;
    }      
}

The following code returns an error message:

Fatal error: Call to undefined method Application\View\Helper\Newsletter::getRequest()...

Do i have to include some additional code that is not mentioned in the tutorial because i'm using the code in the helper file?

You should not be handling the form request from your viewhelper! That is a job for the controller.

Use the viewhelper to get the form, but post to a dedicated page(with it's own controller/action) and handle the form request on that page.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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