ZF2 EmailAddress validator - php

I am creating ZF2 email address validator via factory that has 2 parts, one checks if emaill is already in DB, two: validate the email.
Prblem is that my NoObjectExists validator works just fine, but the acatual Email address validator does not (validator recognises "dsfsfhsadjkfnaskl" as valid email). Here is my code, maybe you guys can spot what is wrong with it?
$factory = new \Zend\InputFilter\Factory();
$input = $factory->createInput(array(
'name' => 'email',
'required' => false,
'filters' => array(
0 => array(
'name' => 'Zend\Filter\StringTrim',
'options' => array(),
),
),
'validators' => array(
0 => array(
'name' => '\DoctrineModule\Validator\NoObjectExists',
'options' => array(
'object_repository' => $this,
'fields' => array('email'),
),
1 => array(
'name' => '\Zend\Validator\EmailAddress',
'options' => array(
'allow' => \Zend\Validator\Hostname::ALLOW_DNS,
'domain' => true,
),
),
),
),
));
return $input;

You have an error in your array nesting. You aren't closing off the containing the NoObjectExists validator so the Email validator is nested inside.
Try the following:
$factory = new \Zend\InputFilter\Factory();
$input = $factory->createInput(array(
'name' => 'email',
'required' => false,
'filters' => array(
0 => array(
'name' => 'Zend\Filter\StringTrim',
'options' => array(),
),
),
'validators' => array(
0 => array(
'name' => '\DoctrineModule\Validator\NoObjectExists',
'options' => array(
'object_repository' => $this,
'fields' => array('email'),
),
),
1 => array(
'name' => '\Zend\Validator\EmailAddress',
'options' => array(
'allow' => \Zend\Validator\Hostname::ALLOW_DNS,
'domain' => true,
),
),
),
));
return $input;

Related

How to create fieldset collection using form factory in zf2

I'm trying to create a form that contains a collection of fieldsets using only array specs and Zend\Form\Factory.
Here is how I create the form using the factory:
$factory = new Zend\Form\Factory();
$fieldset = $factory->createFieldset(array(
'elements' => array(
array(
'spec' => array(
'name' => 'name',
'type' => 'Text',
'attributes' => array(
'class' => 'form-control input-sm',
),
'options' => array(
'label' => 'Name',
),
),
),
array(
'spec' => array(
'name' => 'driverClass',
'type' => 'Text',
'attributes' => array(
'class' => 'form-control input-sm',
),
'options' => array(
'label' => 'Driver',
),
),
),
),
'input_filter' => array(
'name' => array(
'required' => true,
),
),
));
$form = $factory->createForm(array(
'name' => 'application-form',
'attributes' => array(
'role' => 'form',
),
'elements' => array(
array(
'spec' => array(
'type' => 'Collection',
'name' => 'connection',
'options' => array(
'label' => 'Connections',
'allow_add' => true,
'allow_remove' => true,
'should_create_template' => true,
'count' => 2,
'target_element' => $fieldset,
),
),
),
array(
'spec' => array(
'name' => 'security',
'type' => 'Csrf',
'attributes' => array(
'required' => 'required',
),
),
),
array(
'spec' => array(
'name' => 'submit',
'type' => 'Submit',
'attributes' => array(
'class' => 'btn btn-sm btn-primary',
),
'options' => array(
'label' => 'Apply',
),
),
),
),
));
The resulting form works fine when I try to set data and render form elements. But when I validate it and retrieve data, like so (in a controller):
$form->setData($this->getRequest()->getPost());
if ($form->isValid() === true) {
$data = $form->getData();
var_dump($this->getRequest()->getPost());
var_dump($data);
}
With this set of data as POST:
object(Zend\Stdlib\Parameters)[141]
private 'storage' (ArrayObject) =>
array (size=3)
'connection' =>
array (size=2)
0 =>
array (size=2)
'name' => string 'orm_default' (length=11)
'driverClass' => string 'Doctrine\DBAL\Driver\PDOMySql\Driver' (length=36)
1 =>
array (size=2)
'name' => string 'blog' (length=4)
'driverClass' => string 'Doctrine\DBAL\Driver\PDOMySql\Driver' (length=36)
'submit' => string '' (length=0)
'security' => string '20d5c146d8874dc804948e962d5de91b-87c9e4097f9140d259efb5c589a05d6b' (length=65)
The array returned by the call to $form->getData() shows an empty collection:
array (size=3)
'security' => string '20d5c146d8874dc804948e962d5de91b-87c9e4097f9140d259efb5c589a05d6b' (length=65)
'submit' => string '' (length=0)
'connection' =>
array (size=0)
empty
What am I missing?
The expected result is a collection, named 'connection' in this example, containing two arrays representing the two fieldsets as specified by the POST data. I have a feeling this has to do with a missing InputFilter (or at least its specs) because I have managed to obtain the expected result when I implement a fieldset class that extends Zend\Form\Fieldset and implements Zend\InputFilter\InputFilterProviderInterface.
Just discovered this class Zend\Form\InputFilterProviderFieldset which does exactly what I missed.
I added a type in the fieldset specs and changed the input filter specs (which is mandatory) like so:
$fieldset = $factory->createFieldset(array(
'type' => 'Zend\Form\InputFilterProviderFieldset',
'elements' => array(
array(
'spec' => array(
'name' => 'name',
'type' => 'Text',
'attributes' => array(
'class' => 'form-control input-sm',
),
'options' => array(
'label' => 'Name',
),
),
),
array(
'spec' => array(
'name' => 'driverClass',
'type' => 'Text',
'attributes' => array(
'class' => 'form-control input-sm',
),
'options' => array(
'label' => 'Driver',
),
),
),
),
'options' => array(
'input_filter_spec' => array(
'name' => array(
'required' => true,
),
),
),
));
And it works fine now. Hope this helped someone.

zend 2 forms validatator groups

i am using the getInputFilterSpecification() to validate my form elements i.e
public function getInputFilterSpecification()
{
return array(
'comment' => array(
'required' => true,
'filters' =>array(
array('name'=>'StripTags'),
array('name'=>'StringTrim'),
),
'validators' => array(
array(
'name' => 'StringLength',
'options' => array(
'encoding' => 'UTF-8',
'min' => 1,
'max' => 500,
),
),
),
),
'name' => array(
'required' => true,
'filters' =>array(
array('name'=>'StripTags'),
array('name'=>'StringTrim'),
),
'validators' => array(
array(
'name' => 'StringLength',
'options' => array(
'encoding' => 'UTF-8',
),
),
),
),
}
my question is: rather than repeat the same validators for each separate element in my forms, is its possible to lump all the elements into an array and to get the valiators to loop all over them .
i.e somthing like this:
$validateThisGroup = $inputFilter->setValidationGroup(array('comment', 'name'));
return array(
$validateThisGroup => array(
'required' => true,
'filters' =>array(
array('name'=>'StripTags'),
array('name'=>'StringTrim'),
),
'validators' => array(
array(
'name' => 'StringLength',
'options' => array(
'encoding' => 'UTF-8',
'min' => 1,
'max' => 500,
),
),
),
),
UPDATE;
I have reworded my question. I am basically trying to find out if there is a validator group function for the input filter specification function.
Not sure if my advice deserves to be an fully fledged answer but anyways :)
Validators need to be created separately for each input, they are separate stateful instances created by InputFilter's plugin manager, so you need to pass separate definition of validators for each input.
If you just want to avoid copypasting, define validator definition before returning and plug it into return array.
$inputValidatorsSpec = [
[
'name' => 'StringLength',
'options' => [
'encoding' => 'UTF-8',
'min' => 1,
'max' => 500,
],
],
];
$inputFiltersSpec = [
['name' => 'StripTags'],
['name' => 'StringTrim'],
];
return [
'comment' => [
'required' => true,
'filters' => $inputFiltersSpec,
'validators' => $inputValidatorsSpec
],
'name' => [
'required' => true,
'filters' => $inputFiltersSpec,
'validators' => $inputValidatorsSpec
]
];

Translate Zend Form Validation Error Messages?

I have application that runs with different languages. The custom labels, header $this->translate('message') are working perfectly with any problem. I just face problem with translating zend error Message form. Here is what I added it in module.config.php. Could any one help me to display error message form in different languages.
'translator' => array(
'locale' => 'pl',
'translation_file_patterns' => array(
array(
'type' => 'gettext',
'base_dir' => __DIR__ . '/../language',
'pattern' => '%s.mo',
),
array(
'type' => 'phpArray',
'base_dir' => 'vendor/zendframework/zend-i18n-resources/languages',
'pattern' => '%s/Zend_Captcha.php',
'text_domain' => 'formvalidation',
),
array(
'type' => 'phpArray',
'base_dir' => 'vendor/zendframework/zend-i18n-resources/languages',
'pattern' => '%s/Zend_Validate.php',
'text_domain' => 'formvalidation',
),
),
),
This is how I do it within the getInputFilter form function. This way I can retrieve the string in Poedit and proceed with the translations:
public function getInputFilter() {
if (!$this->filter) {
$inputFilter = new InputFilter();
$factory = new InputFactory ();
$inputFilter->add($factory->createInput(array(
'name' => 'email',
'filters' => array(
array(
'name' => 'StripTags'
),
array(
'name' => 'StringTrim'
)
),
'validators' => array(
array(
'name' => 'EmailAddress',
'options' => array(
'messages' => array(
'emailAddressInvalidFormat' => _('Email address format is not invalid')
)
)
),
array(
'name' => 'NotEmpty',
'options' => array(
'messages' => array(
'isEmpty' => _('Email address is required')
)
)
),
array(
'name' => 'StringLength',
'options' => array(
'min'=>6,
'max'=>128,
'messages' => array(
\Zend\Validator\StringLength::TOO_LONG => _('Invalid length for this field')
)
)
)
)
)));
$this->filter = $inputFilter;
}
return $this->filter;
}

ZF2's custom validator's $context suddenly gives 'bar'=>array() when posting bar[0][foo]='xyz'

I have a custom validator using $context that has been working for over a year.
The $context contains all posted parameters except for "bar" which is an empty array although it is posted as bar[0][description]. The array used to contain one or more arrays with key-value-pairs.
This seems to be the case since updating from version 2.3.2 to 2.5.1
I can't even check the 2.5 documentation since it's not available, Google didn't turn up anything close to the issue, ... was the behaviour changed or is this a bug?
Edit:
In .../Lorem/Form/FooForm.php I include a fieldset:
public function __construct() {
// ...
$this->add(array(
'type' => 'Collection',
'name' => 'bar',
'options' => array(
'label'=> '',
'count' => 1,
'should_create_template' => TRUE,
'allow_add' => TRUE,
'use_as_base_fieldset' => TRUE,
'target_element' => array(
'type' => 'Lorem\Fieldset\BarFieldset'
)
)
));
}
In .../Lorem/Fieldset/BarFieldset.php I have:
public function __construct() {
parent::__construct('bar');
$this->setHydrator(new ReflectionHydrator())
->setObject(new Bar());
$this->add(array(
'name' => 'description',
'type' => 'Textarea',
'attributes' => array(
'rows' => 3,
'cols' => 40,
),
));
$this->add(array(
'name' => 'amount',
'attributes' => array(
'type' => 'Text',
'class' => 'input-bar-amount',
'maxlength' => 9,
),
));
// ...
}
public function getInputFilterSpecification()
{
return array(
'description' => array(
'required' => TRUE,
'filters' => array(
array('name' => 'StripTags'),
),
'validators' => array(
array(
'name' => 'NotEmpty',
'break_chain_on_failure' => TRUE,
'options' => array(
'messages' => array(
'isEmpty' => 'Please enter a description.',
),
),
),
),
),
'amount' => array(
'required' => TRUE,
'filters' => array(
array('name' => 'StripTags'),
array('name' => 'StringTrim'),
),
'validators' => array(
array(
'name' => 'NotEmpty',
'break_chain_on_failure' => TRUE,
'options' => array(
'messages' => array(
'isEmpty' => 'Please enter amount.',
),
),
),
array(
'name' => 'Float',
'break_chain_on_failure' => TRUE,
'options' => array(
'locale' => 'de',
'messages' => array(
'floatInvalid' => 'Invalid input. String, Integer oder Float expected.',
'notFloat' => 'Input ist not a floating point number.',
),
),
),
array(
'name' => 'Between',
'break_chain_on_failure' => TRUE,
'options' => array(
'min' => -1000000,
'max' => 1000000,
'messages' => array(
'notBetween' => "Only values between '%min%' and '%max%' EUR are allowed.",
'notBetweenStrict' => "Only values between '%min%' and '%max%' EUR are allowed.",
),
),
),
),
),
// ...
);
}

Rendering and process same form twice in Zend Framework 2?

I have a requirement of rendering and processing the same form again if user check a select box. I looked into form collections but it didn't exactly access my problem because I don't need to render a set of fields instead my requirement is to render the complete form again. So what I added another function getClone($prefix) to get the clone of form which returns me the clone of form object after adding a prefix in the name of form. Like this
<?php
namespace Company\Form;
use Zend\Form\Form;
use Zend\InputFilter\Factory as InputFactory;
use Zend\InputFilter\InputFilter;
use Zend\InputFilter\InputFilterAwareInterface;
use Zend\InputFilter\InputFilterInterface;
class CompanyAddress extends Form implements InputFilterAwareInterface {
protected $inputFilter;
public function __construct($countries, $name = 'null') {
parent::__construct('company_address');
$this->setAttribute('method', 'post');
$this->setAttribute('id', 'company_address');
$this->add(array(
'name' => 'street_1',
'attributes' => array(
'id' => 'street_1',
'type' => 'text',
),
'options' => array(
'label' => 'Street *',
)
));
$this->add(array(
'name' => 'street_2',
'attributes' => array(
'id' => 'street_2',
'type' => 'text',
),
'options' => array(
'label' => 'Street 2',
)
));
$this->add(array(
'name' => 'country_id',
'type' => 'Zend\Form\Element\Select',
'attributes' => array(
'id' => 'country_id',
),
'options' => array(
'label' => 'Country',
'value_options' => $countries
)
));
$this->add(array(
'name' => 'city_id',
'type' => 'Zend\Form\Element\Select',
'attributes' => array(
'id' => 'city_id',
),
'options' => array(
'label' => 'City ',
'value_options' => array()
)
));
$this->add(array(
'name' => 'zip',
'attributes' => array(
'id' => 'zip',
'type' => 'text',
),
'options' => array(
'label' => 'ZIP',
'value_options' => array()
)
));
$this->add(array(
'name' => 'address_type',
'type' => 'Zend\Form\Element\Select',
'attributes' => array(
'id' => 'zip',
),
'options' => array(
'label' => 'Type',
'value_options' => array(
'' => 'Select Type',
'default' => 'Default',
'invoice' => 'Invoice',
'both' => 'Both',
)
)
));
}
public function getClone($prefix){
$form = clone $this;
foreach($form->getElements() as $element){
$name = $element->getName();
$element->setName("$prefix[$name]");
}
return $form;
}
public function getInputFilter() {
if (!$this->inputFilter) {
$inputFilter = new InputFilter();
$factory = new InputFactory();
$inputFilter->add($factory->createInput(array(
'name' => 'street_1',
'required' => true,
'filters' => array(
array('name' => 'StripTags'),
array('name' => 'StringTrim'),
),
'validators' => array(
array(
'name' => 'NotEmpty',
'options' => array('message' => 'Street cannot be empty'),
),
),
)));
$inputFilter->add($factory->createInput(array(
'name' => 'street_2',
'required' => false,
'filters' => array(
array('name' => 'StripTags'),
array('name' => 'StringTrim'),
),
'validators' => array(
),
)));
$inputFilter->add($factory->createInput(array(
'name' => 'city_id',
'required' => true,
'filters' => array(
array('name' => 'StripTags'),
array('name' => 'StringTrim'),
),
'validators' => array(
array(
'name' => 'NotEmpty',
'options' => array('message' => 'City cannot be empty'),
),
),
)));
$inputFilter->add($factory->createInput(array(
'name' => 'country_id',
'required' => true,
'filters' => array(
array('name' => 'StripTags'),
array('name' => 'StringTrim'),
),
'validators' => array(
array(
'name' => 'NotEmpty',
'options' => array('message' => 'Country cannot be empty'),
),
),
)));
$inputFilter->add($factory->createInput(array(
'name' => 'zip',
'required' => true,
'filters' => array(
array('name' => 'StripTags'),
array('name' => 'StringTrim'),
),
'validators' => array(
array(
'name' => 'NotEmpty',
'options' => array('message' => 'ZIP cannot be empty'),
),
),
)));
$inputFilter->add($factory->createInput(array(
'name' => 'address_type',
'required' => true,
'filters' => array(
array('name' => 'StripTags'),
array('name' => 'StringTrim'),
),
'validators' => array(
array(
'name' => 'NotEmpty',
'options' => array('message' => 'Address Type cannot be empty'),
),
),
)));
$this->inputFilter = $inputFilter;
}
return $this->inputFilter;
}
}
and than in my action I did this
public function testAction() {
$countries = $this->getServiceLocator()->get('Country')->getSelect();
$companyAddressForm = new CompanyAddressForm($countries);
$clone = $companyAddressForm->getClone('address2');
if($this->request->isPost()){
$data = $this->request->getPost();
$companyAddressForm->setData($data);
$clone->setData($data['address2']);
$isFormOneValid = $companyAddressForm->isValid();
//$isFormTwoValid = $clone->isValid();
}
$view = new ViewModel();
$view->companyAddressForm = $companyAddressForm;
$view->clone = $clone;
return $view;
}
This is working as I expected it to work, forms are rendering and validating correctly, I want to know whether it is a correct way or a hack?
If both of the forms are exactly the same then you don't need to declare and validate two forms in the controller action.
Reason:
If there are two forms rendered your HTML page. Only one of the forms can be posted by the users at a time and you need to validate only one form at a time. What you are doing now is to validate the same form with the same post data over again. So either $isFormOneValid, $isFormTwoValid are both true or both false.
Instead, declare only one form, render it twice in your view, and upon post, validate it with the post data. If the two forms differ in properties, filters, validators, etc. then you can create two methods like $form->applyForm1Validarots() and $form->applyForm2Validarots, check the value of your select element, and call the appropriate method to apply the validaorts / filters before calling isValid() on it.
Hope I helped

Categories