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
Related
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.",
),
),
),
),
),
// ...
);
}
I have a form with a subform. My question is how to validate that? I don't have any idea how to validate this form with subforms. This is the code:
$this->setAttribute('method', 'post');
$this->add(array(
'name' => 'manual',
'attributes' => array(
'type' => 'hidden',
'value'=>'1',
),
));
$this->add(array(
'name' => 'id',
'attributes' => array(
'type' => 'hidden',
),
));
$subForm = new \Zend\Form\Form();
$subForm->setName('name');
$subForm->add( array(
'name' => 'ca',
'type' => 'text',
));
$subForm->add( array(
'name' => 'en',
'type' => 'text',
));
$subForm->add( array(
'name' => 'es',
'type' => 'text',
));
$this->add($subForm);
$this->add(array(
'name' => 'acronym',
'attributes' => array(
'type' => 'text',
'placeholder' => 'acronym',
'class' => 'docnet-form-acronym-entity',
),
));
$this->add(array(
'name' => 'submit',
'attributes' => array(
'type' => 'submit',
'class' => 'btn',
'value' => 'add',
'id' => 'submitbutton',
),
));
I made this form because I had an array to the element name. To list it it works but now I want to edit and I can't get validated.
I think you should use a Zend\Form\Fieldset instead of a sub form. It makes the validation a lot easier. ZF2 actually has a useful example in the docs on collections.
I am developing an image gallery and I want to check if the input file has a file set or not.
This is my try, where only the title is checked, but if the user hasn't set an image it is not detected, what am I doing wrong?
Form
namespace Backoffice\Form;
use Zend\Form\Form;
class GalerieForm extends Form
{
public function __construct($galerieContent = null)
{
parent::__construct('galerie-form');
$this->setAttribute('action', '/backoffice/galerie/add');
$this->setAttribute('method', 'post');
$this->setAttribute('role', 'form');
$this->setAttribute('enctype', 'multipart/form-data');
$this->setInputFilter(new \Backoffice\Form\GalerieFilter());
$this->add(array(
'name' => 'title',
'attributes' => array(
'type' => 'text',
'id' => 'title',
'value' => $galerieContent->title,
'class' => 'form-control'
),
'options' => array(
'label' => 'Picture Title:',
'label_attributes' => array(
'class' => 'control-label'
)
),
));
$this->add(array(
'name' => 'picture',
'attributes' => array(
'type' => 'file',
'id' => 'picture-selector',
'value' => $galerieContent->picture,
'class' => 'btn btn-file',
),
'options' => array(
'label' => 'Picture:',
'label_attributes' => array(
'class' => 'col-xs-1 control-label',
)
),
));
$this->add(array(
'name' => 'update-from',
'attributes' => array(
'type' => 'hidden',
'value' => 'galerie'
),
));
$this->add(array(
'name' => 'submit',
'attributes' => array(
'type' => 'submit',
'value' => 'Update Gallery Content',
'class' => 'btn btn-primary'
),
));
}
}
InputFilter
namespace Backoffice\Form;
use Zend\Form;
use Zend\InputFilter\InputFilter;
use Zend\Validator\File\IsImage;
class GalerieFilter extends InputFilter
{
public function __construct()
{
$this->add(array(
'name' => 'title',
'required'=> true,
'filters' => array(
array('name' => 'StripTags'),
array('name' => 'StringTrim'),
),
'validators' => array(
array(
'name' => 'StringLength',
'options' => array(
'encoding' => 'UTF-8',
'min' => 1,
'max' => 255,
),
),
),
));
$this->add(array(
'name' => 'picture',
'required'=> true
));
}
}
Controller
public function addAction()
{
if ($this->getRequest()->isPost())
{
$post = array_merge_recursive(
$this->getRequest()->getPost()->toArray(),
$this->getRequest()->getFiles()->toArray()
);
var_dump($post);
$form = new \Backoffice\Form\GalerieForm();
$form->setData($post);
if ($form->isValid()) {
var_dump($post);
}
}
else {
$form = new \Backoffice\Form\GalerieForm();
}
return new ViewModel(array(
'form' => $form
));
}
I had the same problem before, then i putted this into my controller:
if ($request->isPost()) {
$post = array_merge_recursive(
$request->getPost()->toArray(),
$request->getFiles()->toArray()
);
// To get the required error message
if (!$post['picture']['tmp_name']) {
$post['picture'] = null;
}
$form->setData($post);
}
I suggest to extend your InputFilter with an additional Valitator e.g. UploadFile which checks if there is an uploaded file. This would be more maintainable than define an additional validation rule within your controller action.
InputFilter code..
$this->add(array(
'name' => 'picture',
'required' => true,
'validators' => array(
new \Zend\Validator\File\UploadFile()
)
)
ZF2 has several standard validators for File validation and already InputFilters especially for File Uploads.
How i can a validate input data in my from email and password fields, if email field must contains only valid E-mail address and password between 6 and 12 length characters?
My form code:
namespace Notes\Form;
use Zend\Form\Form;
use Zend\InputFilter\InputProviderInterface;
use Zend\InputFilter\InputFilter;
use Zend\Validator\ValidatorInterface;
use Zend\InputFilter\Factory as InputFactory;
class AuthorizationForm extends Form
{
public function __construct($name = null)
{
parent::__construct('auth');
$this->setAttribute('method', 'post');
$this->add(array(
'name' => 'email',
'attributes' => array(
'type' => 'text',
'style' => 'width: 250px;',
),
));
$this->add(array(
'name' => 'password',
'attributes' => array(
'type' => 'password',
'style' => 'width: 250px;',
),
));
$this->add(array(
'name' => 'submit',
'attributes' => array(
'type' => 'submit',
'value' => 'Login',
'id' => 'submitbutton',
'class' => 'fbutton green',
),
));
$this->add(array(
'type' => 'Zend\Form\Element\Checkbox',
'name' => 'save_login',
'options' => array(
'label' => 'Remember me ',
'checked_value' => '1',
),
));
}
}
Thanks for answers!
Add these validators into your Model file:
// For email validation
'validators' => array(
array('regex', true, array(
'pattern' => '/[A-Z0-9._%-]+#[A-Z0-9.-]+\.[A-Z]{2,4}/i',
'messages' => 'Your error message here...'))
),
// For character length validation
'validators' => array(
array(
'name' => 'Between',
'options' => array(
'min' => 6,
'max' => 12,
),
),
),
I hope this helps.
There is inbuilt validator for email validation that will go like this,
'validators' => array(
array('EmailAddress',true)
)
also for more detailed information visit the following,
http://zend-framework-community.634137.n4.nabble.com/ZF2-How-to-validate-a-password-and-email-in-zend-framework-2-td4657533.html
I have set my form for validation using $form->setData().
After validation I am not receiving all of my properties back using $form->getData().
I am using following lines in controller
and somehow $form->getData() is not returning all fields anyone has any idea why?
if ($request->isPost())
{
$company = new Company();
$form->setInputFilter($company->getInputFilter());
$form->setData($request->getPost());
print_r($request->getPost()); // getPost shows all fields fine
if ($form->isvalid())
{
print_r($form->getData()); // is returning only select and text type fields which are in input filter. why?
}
}
my form is looks like this.
class Companyform extends Form
{
public function __construct()
{
parent::__construct('company');
$this->setAttribute ('method', 'post');
$this->setAttribute ('class', 'form-horizontal');
$this->add(array(
'name' => 'id',
'attributes' => array(
'type' => 'hidden'
),
));
$this->add ( array (
'name' => 'title',
'type' => 'Zend\Form\Element\Select',
'attributes' => array(
'id' => 'title',
'options' => array(
'mr' => 'Mr',
'miss' => 'Miss',
'mrs' => 'Mrs',
'dr' => 'Dr'
),
'value' => 'mr'
),
'options' => array(
'label' => 'Title'
)
));
$this->add(array(
'name' => 'fname',
'attributes' => array(
'id' => 'fname',
'type' => 'text',
'placeholder' => "First Name",
),
'options' => array(
'label' => 'First Name'
)
));
$this->add(array(
'name' => 'surname',
'attributes' => array(
'id' => 'surname',
'type' => 'text',
'placeholder' => "Surname Name",
),
'options' => array(
'label' => 'Surname Name'
)
));
$this->add(array(
'name' => 'companyName',
'attributes' => array(
'id' => 'companyName',
'type' => 'text',
'placeholder' => "Company Name",
),
'options' => array(
'label' => 'Company Name'
)
));
$this->add(array(
'name' => 'address1',
'attributes' => array(
'id' => 'address1',
'type' => 'text',
'placeholder' => "Address Line 1",
),
'options' => array(
'label' => 'Address'
)
));
$this->add(array(
'name' => 'address2',
'attributes' => array(
'id' => 'address2',
'type' => 'text',
'placeholder' => "Address Line 2",
),
'options' => array(
'label' => 'Address'
)
));
$this->add(array(
'name' => 'address3',
'attributes' => array(
'id' => 'address3',
'type' => 'text',
'placeholder' => "Address Line 3",
),
'options' => array(
'label' => 'Address'
)
));
$this->add(array(
'name' => 'btnsubmit',
'attributes' => array(
'id' => 'btnsubmit',
'type' => 'submit',
'value' => 'Add',
'class' => 'btn btn-primary'
),
));
}
}
and This is the input filter which I am using in entity company
public function setInputFilter(InputFilterInterface $inputFilter)
{
throw new \Exception("Not used");
}
public function getInputFilter()
{
if (!$this->inputFilter) {
$inputFilter = new InputFilter();
$factory = new InputFactory();
$inputFilter->add($factory->createInput(array(
'name' => 'companyName',
'required' => true,
'filters' => array(
array('name' => 'StripTags'),
array('name' => 'StringTrim'),
),
'validators' => array(
array(
'name' => 'StringLength',
'options' => array(
'encoding' => 'UTF-8',
'min' => 2,
'max' => 255,
),
),
),
)));
$this->inputFilter = $inputFilter;
}
return $this->inputFilter;
}
Every single Form-Element has to get validated! Even if the validator is empty like
$inputFilter->add($factory->createInput(array(
'name' => 'title'
)));
Only validated data get's passed from the form.