Zend Framework 2 FormSubmit calling controller action

How do I connect a submit button to a controllers action, so when I click submit, my controller will fire a specific action?

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();

?>

      

+3


source to share


1 answer


You can use:

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

      



You can get $url

with Url helpers:

  • In view - $this->url('my-route');

  • In the controller - $this->url()->fromRoute('my-route');

+3


source







All Articles