Zend Framework 2 - Building a simple form with Validators - php

I'm trying to build a VERY simple form and want to add the validation in the form itself. No need for million lines of code when adding it in the form just is about 3 lines.
Here are two of my fields:
$this->add(array(
'name' => 'username',
'attributes' => array(
'type' => 'text',
),
'options' => array(
'label' => 'Name*',
'required' => true,
),
'filters' => array(
array('StringTrim')
),
));
$this->add(array(
'name' => 'email',
'attributes' => array(
'type' => 'text',
),
'options' => array(
'label' => 'E-Mail*',
'required' => true,
),
'validators' => array(
array('regex', true, array(
'pattern' => '/[A-Z0-9._%-]+#[A-Z0-9.-]+\.[A-Z]{2,4}/i',
'messages' => 'Bitte eine gültige E-Mailadresse angeben'))
),
'filters' => array(
array('StringTrim')
),
));
The $form->isValid() ALWAYS returns true. Even if the field is empty. I have another field with a regex-validator, same thing... WTF, Zend?
My controller looks like this:
$form = new UserForm();
$form->setHydrator(new DoctrineEntity($entityManager));
$request = $this->getRequest();
if ($request->isPost()) {
$backenduser = new User();
$form->bind($user);
$form->setData($request->getPost());
if ($form->isValid()) {
....
}
Any ideas?

Validation- and Filtering-Definitions aren't part of the Form itself. See http://framework.zend.com/manual/2.0/en/user-guide/forms-and-actions.html

Try this, pass $_POST data.
if($form->isValid($_POST)) {
// success!
} else {
// failure!
}

Related

Zend Framework password field rendering as 'text' instead of 'password'

I'm following along with the Zend Framework 2.0 by example, and working on the Forms chapter now. Everything seems to be working fine, except that my 'password' and 'confirm password' fields don't seem to be rendering correctly. Here is an excerpt of my RegisterForm.php file where I am defining the password field
class RegisterForm extends Form
{
public function __construct($name = null)
{
parent::__construct('Register');
$this->setAttribute('method', 'post');
$this->setAttribute('enctype', 'multipart/form-data');
...
$this->add(array(
'name' => 'password',
'attributes' => array(
'type' => 'password',
),
'options' => array(
'label' => 'Password',
),
'attributes' => array(
'required' => 'required'
),
'filters' => array(
array('name' => 'StringTrim'),
),
));
but when it is rendered in the browser, I am getting this when I view the page source...
<dd><input name="password" required="required" type="text" value=""></dd>
I'm quite sure I've got the code down from the book correctly, but I'm not sure if there's another step where I'm accidentally overriding the RegisterForm.php file.
why are you overriding your attributes? It should be:
$this->add(array(
'name' => 'password',
'options' => array(
'label' => 'Password',
),
'attributes' => array(
'type' => 'password',
'required' => 'required'
),
'filters' => array(
array('name' => 'StringTrim'),
),
));
'attributes' => array(
'type' => 'password',
),
// ...
'attributes' => array(
'required' => 'required'
),
Think a second...

ZF2 form validation is empty validations always fails

Hiho,
i have a problem with a ZF2 Form.
Every time I submit it I got the following error:
(result of $form->isValid() and var_dump($form->getMessages());
array (size=1)
'imagecode' =>
array (size=1)
'isEmpty' => string 'Value is required and can't be empty' (length=36)
The following is the 'imagecode' - formfieldcode:
public function __construct($name = null)
{
parent::__construct('advert');
$this->setAttribute('method', 'post');
$this->add(array(
'name' => 'imagecode',
'type' => 'Zend\Form\Element\Textarea',
'attributes' => array(
'required' => 'required',
),
'options' => array(
'label' => 'Bannercode:'
),
));
And the Validator:
public function getInputFilter()
{
if (!$this->_inputFilter) {
$inputFilter = new InputFilter();
$factory = new InputFactory();
...
$inputFilter->add($factory->createInput(array(
'name' => 'imagecode',
'required' => true,
'filters' => array(
array('name' => 'StripTags'),
array('name' => 'StringTrim'),
),
'validators' => array(
array(
'name' => 'StringLength',
'options' => array(
'min' => '3',
'max' => '5000',
),
),
),
)));
$this->_inputFilter = $inputFilter;
}
return $this->_inputFilter;
}
The other fields working correct and are correct validated but not the Textarea.
At last the ControllerCode:
$advert = $service->getAdvertById($id);
$form = $service->getAdvertForm();
$request = $this->getRequest();
$form->bind($advert);
if ($request->isPost()) {
$filter = new AdvertFilter();
$form->setData($request->getPost());
$form->setInputFilter($filter->getInputFilter());
After this the validation is failing and I don't know why.
I hope that any one can help me.
Look this line :
'required' => 'required,
and....
change to:
'required' => 'required',
I have figured it out.
I trying to input html code so that the
array('name' => 'StripTags')
removed it.
Sometimes it is so simple ._.'

Create Login form in zend framework2

I am trying to create login page in zend framework2. I have created its view,controller,model and form. Even i m not getting any error.
following my code :
My model as Login.php is :
class Login implements InputFilterAwareInterface
{
public $id;
public $username;
public $password;
protected $inputFilter;
public function exchangeArray($data)
{
$this->id = (!empty($data['id'])) ? $data['id'] : null;
$this->username = (!empty($data['username'])) ? $data['username'] : null;
$this->password = (!empty($data['password'])) ? $data['password'] : null;
}
public function getArrayCopy()
{
return get_object_vars($this);
}
public function setInputFilter(InputFilterInterface $inputFilter)
{
throw new \Exception("Not used");
}
public function getInputFilter()
{
if (!$this->inputFilter) {
$inputFilter = new InputFilter();
$inputFilter->add(array(
'name' => 'id',
'required' => true,
'filters' => array(
array('name' => 'Int'),
),
));
$inputFilter->add(array(
'name' => 'username',
'required' => true,
'filters' => array(
array('name' => 'StripTags'),
array('name' => 'StringTrim'),
),
'validators' => array(
array(
'name' => 'StringLength',
'options' => array(
'encoding' => 'UTF-8',
'min' => 1,
'max' => 100,
),
),
),
));
$inputFilter->add(array(
'name' => 'password',
'required' => true,
'filters' => array(
array('name' => 'StripTags'),
array('name' => 'StringTrim'),
),
'validators' => array(
array(
'name' => 'StringLength',
'options' => array(
'encoding' => 'UTF-8',
'min' => 1,
'max' => 100,
),
),
),
));
$this->inputFilter = $inputFilter;
}
return $this->inputFilter;
}
}
My LoginForm is :
namespace Application\Form;
use Zend\Form\Form;
class LoginForm extends Form
{
public function __construct($name = null)
{
// we want to ignore the name passed
parent::__construct('tbluser');
$this->add(array(
'name' => 'id',
'type' => 'Hidden',
));
$this->add(array(
'name' => 'username',
'type' => 'Text',
'options' => array(
'label' => '',
),
'attributes' => array(
'id' => 'username',
'class'=>'',
'autocomplete'=>'OFF',
'max'=>'100',
),
));
$this->add(array(
'name' => 'password',
'type' => 'Text',
'options' => array(
'label' => '',
),
'attributes' => array(
'id' => 'password',
'class'=>'',
'autocomplete'=>'OFF',
'max'=>'100',
),
));
$this->add(array(
'name' => 'submit',
'type' => 'Submit',
'attributes' => array(
'value' => 'Login',
'id' => 'login',
'class'=>'btn btn-success',
),
));
}
}
and my controller action code is :
public function indexAction()
{
$form = new LoginForm();
$request = $this->getRequest();
$user=new LoginTable();
if ($request->isPost()) {
$login = new Login();
$form->setInputFilter($login->getInputFilter());
$form->setData($request->getPost());
if ($form->isValid()) {
$data=$login->exchangeArray($form->getData());
$user->getUser($this->$username,$this->$password);
if($user){
return $this->redirect()->toRoute('album', array(
'action' => 'album'));
}else{
return array('form' => $form);
}
}
}
return array('form' => $form);
}
my form is not validating at this statement "if ($form->isValid()){}" the exicution is not entering in this statement. I searched out every thing but not able to find solution what i m missing. Can any body help me to get out of this.
Looking at the form it looks as if you have an input filter attached to the hidden field id. If you are looking to register the user you obviously will not have their id before authentication.
You can test this by adding a else statement of your form and checking the forms messages (because the element is hidden you will not see it output otherwise)
if ($form->isValid()) {
// Is valid code here
} else {
print_r($form->getMessages());
}
This will probably output and array with the message "id - this element cannot be empty" or something similar.
The solution would be to remove the id input filter from the form (and probably the id form element as I can't see how this would be needed).

Zend Framework2 : Post is not working correctly

I am a Zend Framework beginner.
I guess My question is very basic... but I can't solve it by myself.
In indexAction, $request->isPost() is always false.
What is happening?
EntryController::indexAction
public function indexAction() {
$form = new AgreementForm();
$form->get('submit')->setValue('Go Entry Form');
$request = $this->getRequest();
if ($request->isPost()) {
var_dump('//// $request->isPost() is true //////');
if ($form->get('agreementCheck')) {
// Redirect to list of entries
return $this->redirect()->toRoute('entry');
} else {
return array('form' => $form);
}
} else {
var_dump('//// $request->isPost() is false //////');
return array('form' => $form);
}
}
form in index.phtml
<?php
$form = $this->form;
$form->setAttribute('action', $this->url('entry', array('action' => 'index')));
$form->prepare();
echo $this->form()->openTag($form);
echo $this->formCheckbox($form->get('agreementCheck'));
echo $this->formSubmit($form->get('submit'));
echo $this->form()->closeTag();
?>
AgreementForm is generated using code generator.
http://zend-form-generator.123easywebsites.com/formgen/create
as below.
class AgreementForm extends Form {
public function __construct($name = null) {
parent::__construct('');
$this->setAttribute('method', 'post');
$this->add(array(
'name' => 'agreementCheck',
'type' => 'Zend\Form\Element\MultiCheckbox',
'attributes' => array(
'required' => 'required',
'value' => '0',
),
'options' => array(
'label' => 'Checkboxes Label',
'value_options' => array(
'0' => 'Checkbox',
),
),
));
$this->add(array(
'name' => 'csrf',
'type' => 'Zend\Form\Element\Csrf',
));
$this->add(array(
'name' => 'submit',
'attributes' => array(
'type' => 'submit',
'value' => 'Go',
'id' => 'submitbutton',
),
));
}
}
Please tell me some hints.
update:
In the result of analysis by Developer Tools, POST and GET works at the same time.
update:
router definition #module.config.php is this.
'router' => array(
'routes' => array(
'entry' => array(
'type' => 'segment',
'options' => array(
'route' => '/entry[/][:action][/:id]',
'constraints' => array(
'action' => '[a-zA-Z][a-zA-Z0-9_-]*',
'id' => '[0-9]+',
),
'defaults' => array(
'controller' => 'Entry\Controller\Entry',
'action' => 'index',
),
),
),
'home' => array(
'type' => 'Zend\Mvc\Router\Http\Literal',
'options' => array(
'route' => '/',
'defaults' => array(
'controller' => 'Entry\Controller\Entry',
'action' => 'index',
),
),
),
),
),
A few things are wrong:
In the form class you add a csrf element, but you don't render it in the view. This will cause a validation error. So you need to add this to your view:
echo $this->formHidden($form->get('csrf'));
You're adding a Multicheckbox element to the form, but in your view you're using the formCheckbox view helper to render it. If you really want a Multicheckbox then you should render it with the formMultiCheckbox helper:
echo $this->formMultiCheckbox($form->get('agreementCheck'));
After these changes it should work.
Edit: Also you may want to pass a name to the form constructor:
parent::__construct('agreementform');
I think, you do not need to explicitly say
$form->setAttribute('action', $this->url('entry', array('action' => 'index')));
Omit that line, and see what happens.

How to validate multiply select using Zend Framework 2

I am trying to validate a multiply select using input filter, but every time I see a error. The error is "notInArray":"The input was not found in the haystack".(I use ajax but it doesn`t metter).
I will show part of my code to be more clear.
in Controller:
if ($request->isPost()) {
$post = $request->getPost();
$form = new \Settings\Form\AddUserForm($roles);//
$form->get('positions')
->setOptions(
array('value_options'=> $post['positions']));
//.... more code...
When I put print_r($post['positions']); I see:
array(0 => 118, 1 => 119)
in ..../form/UserForm.php I create the multiply element
$this->add(array(
'type' => 'Zend\Form\Element\Select',
'attributes' => array(
'multiple' => 'multiple',
'id' => 'choosed_positions',
),
'required' => false,
'name' => 'positions',
));
and in the validation file the code is:
$inputFilter->add($factory->createInput(array(
'name' => 'positions',
'required' => false,
'validators' => array(
array(
'name' => 'InArray',
'options' => array(
'haystack' => array(118,119),
'messages' => array(
'notInArray' => 'Please select your position !'
),
),
),
),
What can be the reason every time to see this error, and how I can fix it?
By default selects have attached InArray validator in Zend Framework 2.
If you are adding new one - you will have two.
You should disable default one as follow:
$this->add(array(
'type' => 'Zend\Form\Element\Select',
'options' => array(
'disable_inarray_validator' => true, // <-- disable
),
'attributes' => array(
'multiple' => 'multiple',
'id' => 'choosed_positions',
),
'required' => false,
'name' => 'positions',
));
And you should get rid of the additional error message.
Please let us know if that would helped you.

Categories