Hi there,
I’m getting a little tied up with Zend forms. There seems to be a number of different ways to set up a form in zf2, and I can’t seem to get to the crux of what I’m trying to achieve.
I wan’t to set up a simple form with validation, so that when its processed I can check the isValid() method, and then handle the post data accordingly. Here’s what I’ve got so far:
<?php
namespace MyForm\\Form;
use Zend\\Form\\Form;
class MyForm extends Form{
public function __construct($name = null){
parent::__construct('MyForm');
$this->setAttribute('method', 'post');
$this->add(
array(
'name' => 'id',
'type' => 'Hidden'
'validators' => array(
'required' => true
)
)
);
$this->add(
array(
'name' => 'name',
'type' => 'Text',
'attributes' => array(
'placeholder' => 'Name'
),
'validators' => array(
'required' => true
)
)
);
$this->add(
array(
'name' => 'email',
'type' => 'Email',
'attributes' => array(
'placeholder' => 'Email'
),
'validators' => array(
'required' => true
)
)
);
$this->add(
array(
'name' => 'submit',
'type' => 'Submit',
'attributes' => array(
'value' => 'Go'
)
)
);
}
}
…and the controller
namespace MyForm\\Controller;
use Zend\\Mvc\\Controller\\AbstractActionController;
use Zend\\View\\Model\\ViewModel;
use Application\\Model\\Application;
use MyForm\\Form\\MyForm;
class MyFormController extends AbstractActionController
{
public function indexAction()
{
$form = new MyForm($status);
$request = $this->getRequest();
if($request->isPost()){
$form->setData($request->getPost());
if($form->isValid()){
echo "VALID";
} else {
echo "INVALID";
}
}
return new ViewModel(array('form' => $form));
}
}
…and finally the view
<h1>MyForm</h1>
<?php
echo $this->form()->openTag($form);
echo $this->formHidden($form->get('id'));
echo $this->formRow($form->get('name'));
echo $this->formRow($form->get('email'));
echo $this->formRow($form->get('submit'));
echo $this->form()->closeTag();
?>
Its rendering the form fine, but isValid() always returns false, and there are no error messages displayed on the form.
Any ideas anyone?
Many thanks in advance,
Mike