Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Zend Framework 2 FormSubmit invoking a controller action

How do I connect a 'submit' button to a controllers action, so when I press the 'Submit' my controller will have a specific action triggered?

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

?>
like image 772
KaiserJohaan Avatar asked Apr 11 '26 04:04

KaiserJohaan


1 Answers

You can use:

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

You can get $url by using the Url helpers:

  • In a View - $this->url('my-route');
  • In a Controller - $this->url()->fromRoute('my-route');
like image 99
DrBeza Avatar answered Apr 13 '26 20:04

DrBeza