In Zend Framework 2, how do you change the message in the DateStep validator - zend-framework2

In \Zend\Validator\DateStep, I want to override the error message shown below:
protected $messageTemplates = array(
self::NOT_STEP => "The input is not a valid step"
);
I have an input filter connected to a form containing an element of the type 'Zend\Form\Element\Date' which automatically calls the DateStep validator.
Here is the relevant part of my form:
$this->add(array(
'type' => 'Zend\Form\Element\Date',
'name' => 'appointment-date',
'options' => array(
'label' => 'Appointment Date',
'format' => 'Y-m-d'
),
'attributes' => array(
'min' => date('Y-m-d'), // today's date
'max' => '2020-01-01',
'step' => '2', // days; default step interval is 1 day
)
));
Here is my input filter:
$inputFilter->add($factory->createInput(array(
'name' => 'appointment-date',
'required' => false,
'filters' => array(
array('name' => 'StripTags'),
),
'validators' => array(
array(
'name' => 'DateStep',
'options' => array(
//'step' => new DateInterval("P2D"),
//'baseValue' => new DateTime(),
'messages' => array(
\Zend\Validator\DateStep::NOT_STEP => 'Must be a day in the future',
),
),
),
),
)));
The inputFilter seems to be ignored. I tried setting up the step and baseValue in the inputFilter, but that seems to not work at all. Working app can be found here: https://github.com/bickerstoff/zf2_datetest if more details are needed.

Looks like you're trying to filter a "Date" input with a "DateStep" validator.
$this->add(array(
'type' => 'Zend\Form\Element\Date',
'name' => 'appointment-date',
'options' => array(
'label' => 'Appointment Date',
'format' => 'Y-m-d'
),
'attributes' => array(
'min' => date('Y-m-d'), // today's date
'max' => '2020-01-01',
'step' => '2', // days; default step interval is 1 day
)
));
This may cause your problem.

Related

Get an input validator from a form object in zf2

I have the following input filter:
'term' => array(
'required' => false,
'filters' => array(
array(
'name' => 'StringTrim',
)
),
'validators' => array(
array(
'name' => 'StringLength',
'options' => array(
'max' => 128
)
)
)
),
I need to get programmatically from a form object the value of the 'max' option inside the 'validators' property.
$vc = $form->getInputFilter()->get('term')->getValidatorChain()->getValidators();
foreach($vc as $v){
if($v['instance'] instanceof \Zend\Validator\StringLength)
$max = $v['instance']->getMax();
}

ZF2: 'required' => false ignored for DateSelect element

In a Zend Framework 2 application, I have the following form in my controller action method:
public function testAction()
{
$form = new \Zend\Form\Form('test');
$date = new \Zend\Form\Element\DateSelect('date');
$date->setOptions(array(
'label' => 'Date',
'min_year' => date('Y') - 10,
'max_year' => date('Y') + 10,
)
);
$date->getDayElement()->setEmptyOption('day');
$date->getMonthElement()->setEmptyOption('month');
$date->getYearElement()->setEmptyOption('year');
$form->add($date);
$form->add(array(
'name' => 'submit',
'attributes' => array(
'type' => 'submit',
'value' => 'submit',
'id' => 'submitbutton',
),
));
if ($this->request->isPost()) {
$data = $this->request->getPost();
$form->setData($data);
if ($form->isValid()) {
$data = $form->getData();
// more code
}
}
return array('form' => $form);
}
Now if I submit the form I get the validation message:
'The input does not appear to be a valid date'
That is correct but I would only want to know if the field is required. If I look in the source of the DateSelect element, I see a getInputSpecification() method that sets required to false by default and there also is a getValidator() method requiring a format with which the empty date does not comply.
How can I bypass validation if the input is not required (obviously, in my real form I have more elements)?
I usually use the factory pattern and you can set whether the field is required ie
$inputFilter->add($factory->createInput(array(
'name' => 'availableDate',
'required' => true,
'filters' => array(
array('name' => 'StripTags'),
array('name' => 'StringTrim'),
),
'validators' => array(
array(
'name' => 'StringLength',
'options' => array(
'encoding' => 'UTF-8',
'max' => 20,
),
),
),
)));
refer the field required - you can set this to false

zend framework 2.0 fill option from database

i have my application based in ZendSkeletonApplication , now i want create to relationship between my models so:
user portal
id id
firstName name
lastName url
........
portal_Id
I want to fill my select-option in the user form with database values
<?php
namespace Register\Form;
use Zend\Captcha\AdapterInterface as CaptchaAdapter;
use Zend\Form\Form;
use Zend\Form\Element;
class UserForm extends Form
{
protected $portalTable;
public function __construct($name = null)
{
parent::__construct('user');
$this->setAttribute('method', 'post');
$this->setAttribute('class', 'form-horizontal');
$this->add(array(
'name' => 'id',
'attributes' => array(
'type' => 'hidden',
),
));
$this->add(array(
'type' => 'Select',
'name' => 'portal_id',
'options' => array(
'label' => 'Portal',
'empty_option' => 'Seleccione un portal',
'value_options' => array(
'1' => 'portal 1',
'2' => 'portal 2',
'3' => 'portal 3',
//i want option from database with
),
)
));
$this->add(array(
'name' => 'firstName',
'attributes' => array(
'type' => 'text',
),
'options' => array(
'label' => 'First Name',
),
));
$this->add(array(
'name' => 'lastName',
'attributes' => array(
'type' => 'text',
),
'options' => array(
'label' => 'Last Name',
),
));
$this->add(array(
'name' => 'login',
'attributes' => array(
'type' => 'text',
),
'options' => array(
'label' => 'Login',
),
));
$this->add(array(
'name' => 'password',
'attributes' => array(
'type' => 'password',
),
'options' => array(
'label' => 'Password',
),
));
$this->add(array(
'name' => 'password_repeat',
'attributes' => array(
'type' => 'password',
),
'options' => array(
'label' => 'password (repeat)',
),
));
$this->add(array(
'name' => 'email',
'attributes' => array(
'type' => 'text',
),
'options' => array(
'label' => 'Email',
),
));
$this->add(array(
'type' => 'Zend\Form\Element\Csrf',
'name' => 'csrf',
'options' => array(
'csrf_options' => array(
'timeout' => 600
)
)
));
$this->add( array(
'type' => 'Captcha',
'name' => 'captcha',
'options' => array(
'label' => 'Please verify you are human.',
'captcha' => array('class' => 'Dumb',
),
),
));
$this->add(array(
'name' => 'submit',
'attributes' => array(
'type' => 'submit',
'value' => 'Go',
'id' => 'submitbutton',
),
));
}
}
in this part i want fill select from database
$this->add(array(
'type' => 'Select',
'name' => 'portal_id',
'options' => array(
'label' => 'Portal',
'empty_option' => 'Seleccione un portal',
'value_options' => array(
'1' => 'portal 1',
'2' => 'portal 2',
'3' => 'portal 3',
//i want option from database with
),
)
));
sorry for my English
I have written an in-depth blog "Zend\Form\Element\Select and Database-Values" about this topic. Basically though, this is what you have to do:
Basically all you have to do is Query the Database inside your Form for the Data. For this you need the DB-Adapter to be available inside your Form, which is done by Dependency-Injection. Since the DB-Adapter is required for your Form to function correctly, i'd suggest Setter-Injection.
Inside your getServiceConfig() do this:
return array('factories' => array(
'namespace-form-formname' => function($sm) {
$dbA = $sm->get('Zend\Db\Adapter\Adapter');
$form = new \Namespace\Form\Formname($dbA);
return $form;
}
));
This will inject the Zend\Db\Adapter\Adapter into your form, which should already be valid though other configuration. Then you need to modify your form code a little bit:
public function __construct(\Zend\Db\Adapter\Adapter $dbA) {
parent::__construct('form-name');
// Do the DB-Query here. You got the DB-Adapter
// http://zf2.readthedocs.org/en/latest/modules/zend.db.adapter.html
$selectArray = array(
'key' => 'value',
'key' => 'value',
'key' => 'value',
); // obviously, this is just a fake-$selectArray demonstrating
// what the output of your Queries should be
// Add your Form Elements here
// use $selectArray as value_options of your desired select element
}
And that's basically it. Sadly i can't give you an concrete example, as i've never worked with Zend\Db, but i assume this will get you started.
PS: In your controller, call the form like this:
$form = $this->getServiceLocator()->get('namespace-form-formname');
Try:
// add code on controller
$arrPortalId = array();
$results = array('1' => 'portal 1', '2' => 'portal 2', '3' => 'portal 3',); // this part change your database value
foreach ($results as $key => $val) {
$arrPortalId[$key] = $va;
}
$dataParams['portalId'] = $arrPortalId;
$form = new UserForm($dataParams);
<?php
namespace Register\Form;
use Zend\Captcha\AdapterInterface as CaptchaAdapter;
use Zend\Form\Form;
use Zend\Form\Element;
class UserForm extends Form
{
protected $portalTable;
public function __construct($params = array())
{ $name = isset($params['name'])?$params['name']:'';
parent::__construct('user');
$this->setAttribute('method', 'post');
$this->setAttribute('class', 'form-horizontal');
$this->add(array(
'name' => 'id',
'attributes' => array(
'type' => 'hidden',
),
));
$portalId = (isset($params['portalId']) && count($params['portalId']) > 0)?$params['portalId']:array();
$this->add(array(
'type' => 'Select',
'name' => 'portal_id',
'options' => array(
'label' => 'Portal',
'empty_option' => 'Seleccione un portal',
'value_options' => $portalId,
)
));
$this->add(array(
'name' => 'firstName',
'attributes' => array(
'type' => 'text',
),
'options' => array(
'label' => 'First Name',
),
));
$this->add(array(
'name' => 'lastName',
'attributes' => array(
'type' => 'text',
),
'options' => array(
'label' => 'Last Name',
),
));
$this->add(array(
'name' => 'login',
'attributes' => array(
'type' => 'text',
),
'options' => array(
'label' => 'Login',
),
));
$this->add(array(
'name' => 'password',
'attributes' => array(
'type' => 'password',
),
'options' => array(
'label' => 'Password',
),
));
$this->add(array(
'name' => 'password_repeat',
'attributes' => array(
'type' => 'password',
),
'options' => array(
'label' => 'password (repeat)',
),
));
$this->add(array(
'name' => 'email',
'attributes' => array(
'type' => 'text',
),
'options' => array(
'label' => 'Email',
),
));
$this->add(array(
'type' => 'Zend\Form\Element\Csrf',
'name' => 'csrf',
'options' => array(
'csrf_options' => array(
'timeout' => 600
)
)
));
$this->add( array(
'type' => 'Captcha',
'name' => 'captcha',
'options' => array(
'label' => 'Please verify you are human.',
'captcha' => array('class' => 'Dumb',
),
),
));
$this->add(array(
'name' => 'submit',
'attributes' => array(
'type' => 'submit',
'value' => 'Go',
'id' => 'submitbutton',
),
));
}
}

How can I insert an id or class attribute into an option of a select statement in the form of ZF2?

Currently, I have this select code in ZF2. Works great, have no issues, BUT! I want to put an id or class attribute into one of the options. Is that possible currently in ZF2?
$this->add(
array(
'name' => 'number_of_rooms',
'type' => 'Zend\Form\Element\Select',
'options' => array(
'label' => 'Number of Rooms',
'options' => array(
array(
'value' => '',
'label' => '- number of rooms -',
'disabled' => true,
),
array(
'value' => 'one bedrooms,
'label' => '1 Bedrooms',
),
array(
'value' => 'two bedrooms',
'label' => '2 Bedrooms',
),
array(
'value' => 'three bedrooms',
'label' => '3 Bedrooms',
),
),
),
'attributes' => array(
'id' => 'number_of_rooms',
),
)
);
You would need to do two things. First would be to write your own SelectElement extending Zend\Form\Element\Select and then you'd need to also write your own ViewHelper rendering the Select, easiest extending Zend\Form\View\Helper\FormSelect
With the inbuilt Select the only valid options are:
//FormSelect.php #43-48
protected $validOptionAttributes = array(
'disabled' => true,
'selected' => true,
'label' => true,
'value' => true,
);
You can check this from the classes linked above.

zendframework 2 inputfilter customize default error message

I am trying to customize the default error message "Value is required and can't be empty"
in zf2
I am using following code to add customise default error message in validators of inputfilter
$inputFilter->add($factory->createInput(array(
'name' => 'username',
'required' => true,
'filters' => array(
array('name' => 'StripTags'),
array('name' => 'StringTrim'),
),
'validators' => array(
array(
'name' => 'StringLength',
'options' => array(
'encoding' => 'UTF-8',
'min' => 4,
'max' => 20,
'messages' => array(
'isEmpty' => 'Please enter User Name between 4 to 20 character!'
),
),
),
),
)));
But I am getting following error.
Zend\Validator\Exception\InvalidArgumentException
File:
/home/website/vendor/zendframework/zendframework/library/Zend/Validator/AbstractValidator.php:220
Message:
No message template exists for key 'isEmpty'
What I am doing wrong?
reference
try this
$inputFilter->add($factory->createInput(array(
'name' => 'username',
'required' => true,
'filters' => array(
array('name' => 'StripTags'),
array('name' => 'StringTrim'),
),
'validators' => array(
array(
'name' =>'NotEmpty',
'options' => array(
'messages' => array(
\Zend\Validator\NotEmpty::IS_EMPTY => 'Please enter User Name!'
),
),
),
array(
'name' => 'StringLength',
'options' => array(
'encoding' => 'UTF-8',
'min' => 4,
'max' => 20,
'messages' => array(
'stringLengthTooShort' => 'Please enter User Name between 4 to 20 character!',
'stringLengthTooLong' => 'Please enter User Name between 4 to 20 character!'
),
),
),
),
)));
reference
Other validator set
You also can set the error message of inputFilter so:
$form = new ParticipantForm();
$mailInput = new Input('mail');
$mailInput->setRequired(true);
$mailInput->setErrorMessage("Empty input");
The StringLength validator does not check for the input to be empty or not. It checks against lengths. Following message templates exist for StringLength validator:
const INVALID = 'stringLengthInvalid';
const TOO_SHORT = 'stringLengthTooShort';
const TOO_LONG = 'stringLengthTooLong';
/**
* #var array
*/
protected $messageTemplates = array(
self::INVALID => "Invalid type given. String expected",
self::TOO_SHORT => "The input is less than %min% characters long",
self::TOO_LONG => "The input is more than %max% characters long",
);
See the example of #Developer for a direct approach. Though i suggest going with the CamelCased naming of the Validators, so 'name' => 'NotEmpty' instead of 'name' => 'not_empty'
You can check which messageTemplates exist if you see the code for each of the validator classes. You will find them under ./vendor/zendframework/zendframework/library/Zend/Validator/*

Resources