In Zend Framework 2, I've created a class that extends Zend\Form\Form
called MyForm
.
In the indexAction
of one Controller class, I'll initialize MyForm
like this:
public function indexAction()
{
$form = new MyForm('my-name');
$viewModel = new ViewModel(array('form' => $form));
return $viewModel;
}
Then in the corresponding view, I basically just do
$form = $this->form;
$form->prepare();
echo $this->form()->openTag($this->form);
echo $this->formCollection($form);
echo $this->form()->closeTag();
This all works, but you may have noticed that the action for the form is missing.
I have tried to add the action like this in the view:
$form->setAttribute('action', $this->url(NULL, array('controller'=>'Index', 'action' => 'go')));
Then in the go action inside my IndexController I just have this for testing:
public function goAction()
{
die('huh');
}
This did not work at all, I always land at the form view (== index action) again. Why is the go action never executed?
I also know that I could either hardcode the action attribute and let a segment route handle the processing, or I could even define an own route for that.
In what cases form actions should get their own route?
In what cases form actions should be handled using a segment route?
In what cases form actions should be handled like in my example?
If there are no hard rules for this: What intention do the different approaches communicate?
Is it also possible to add form actions in the controller instead of the view?
Continuing on from the comments: That's not how the URL helper works - if you omit the first parameter, the current route is used instead. That's probably why you're not getting the form action you expect.
Personally, I always specify the route name when using the URL helper - makes things clearer.