Zend Framework 2 FormSubmit调用控制器操作

时间:2013-02-06 13:27:23

标签: php html zend-framework2

如何将“提交”按钮连接到控制器操作,因此当我按下“提交”时,我的控制器会触发特定操作?

myController的:

class MyController extends AbstractActionController
{
    public function viewAction()
    {
        $form = new MyForm();
        $viewModel = new ViewModel(array('form' => $form));
        $viewModel->setTemplate('myForm');

        return $viewModel;
    }

    public function submitAction()
    {
       // want to trigger this
    }
}

MyForm的:

class MyForm extends Form
{
    public function __construct()
    {
        parent::__construct('SubmitForm');
        $this->setAttribute('method', 'post');


        $this->add(array(   'name'      => 'submit',
                            'type'      => 'Zend\Form\Element\Submit',
                            'attributes' => array('type'    => 'submit',
                                                  'value'   => 'Submit',
                                                  'id'      => 'submitButton'),
        ));
    }

}

myForm.phtml:

<?php 

$form = $this->form;
$form->prepare();

echo $this->form()->openTag($form);
echo $this->formSubmit($form->get('submit'));    // I want pressing this element should route to MyController::submitAction...
echo $this->form()->closeTag();

?>

1 个答案:

答案 0 :(得分:3)

您可以使用:

$form->setAttribute('action', $url);

您可以使用Url帮助程序获取$url

  • 在视图中 - $this->url('my-route');
  • 在控制器中 - $this->url()->fromRoute('my-route');