I would like add a new validator (using inputFilter) into my collection.
The current code is as follows:
My Code Form:
namespace EventyEvent\Form;
use Zend\Form\Element;
use Zend\Form\Form;
use Zend\InputFilter\InputFilter;
use Zend\Stdlib\Hydrator\ClassMethods as ClassMethodsHydrator;
class EventEditBasicForm extends Form
{
public function __construct(){
parent::__construct();
$this ->setName('event')
->setAttribute('method', 'post')
->setAttribute("accept-charset", "UTF-8")
->setHydrator(new ClassMethodsHydrator(false))
->setInputFilter(new InputFilter());
// date
$this->add(array(
'type' => 'Zend\Form\Element\Collection',
'name' => 'dates',
'options' => array(
'label' => "Dates of your event",
'count' => 1,
'target_element' => array(
'type' => 'EventyEvent\Form\Basic\DateFieldset'
)
)
));
}
My Code Fieldset:
namespace EventyEvent\Form\Basic;
use EventyEvent\Entity\EventDates;
use Zend\Form\Fieldset;
use Zend\InputFilter\InputFilterProviderInterface;
use Zend\Stdlib\Hydrator\ClassMethods as ClassMethodsHydrator;
class DateFieldset extends Fieldset implements InputFilterProviderInterface{
public function __construct()
{
parent::__construct('EventDates');
$this->setHydrator(new ClassMethodsHydrator(false))
->setObject(new EventDates());
// date start
$this->add(array(
'name' => 'datestart',
'attributes' => array(
'required' => 'required',
'type'=>'Text',
),
'options'=>array(
'label'=>"Date start",
)
));
// date end
$this->add(array(
'name' => 'dateend',
'attributes' => array(
'required' => 'required',
'type'=>'Text',
),
'options'=>array(
'label'=>"Date end",
)
));
}
/**
* #return array
*/
public function getInputFilterSpecification()
{
return array(
'datestart' => array(
'required' => true,
'validators' => array(
array(
'name' => 'Date',
'options' => array(
'format' => 'd F Y - H:i'
),
),
),
),
'dateend' => array(
'required' => true,
'validators' => array(
array(
'name' => 'Date',
'options' => array(
'format' => 'd F Y - H:i'
),
),
),
),
);
}
}
I want to add a validator date is later before validation in my controller, but can I? Any tips, corrections or suggestions?
One way to do this is to get the validator chain for the fieldset field from the forms input filter and then just attach your own validator to the chain.
Assuming you have some imaginary DateIsLaterValidator to attach, here's an example to add that validator to the dateend field.
$form = new EventEditBasicForm;
$dateValidators = $form->getInputFilter()->get('dates')
->get('dateend')
->getValidatorChain();
$dateLaterValidator = new DateIsLaterValidator;
$dateValidators->attach($dateLaterValidator);
Related
I have a problem in validating the array of value of an element. I search a lot find a callback function to validate that data.
Below is the validation code which i am using but it is not working
<?php
namespace Tutorials\Form;
use Zend\InputFilter\Factory as InputFactory; // <-- Add this import
use Zend\InputFilter\InputFilter; // <-- Add this import
use Zend\InputFilter\InputFilterAwareInterface; // <-- Add this import
use Zend\InputFilter\InputFilterInterface;
use Zend\Validator\Callback;
use Zend\I18n\Validator\Alpha;
class AddSubTopicFilterForm extends InputFilter implements InputFilterAwareInterface {
protected $inputFilter;
public $topicData;
public $subTopicData;
function __construct($data = array()) {
$articles = new \Zend\InputFilter\CollectionInputFilter();
$articlesInputFilter = new \Zend\InputFilter\InputFilter();
$articles->setInputFilter($articlesInputFilter);
$this->add(new \Zend\InputFilter\Input('title'));
$this->add($articles, 'articles');
if(!empty($data['data']['topic_name'])) {
$this->topicData = $data['data']['topic_name'];
}
if(!empty($data['data']['sub_topic_name'])) {
$this->subTopicData = $data['data']['sub_topic_name'];
}
}
public function setInputFilter(InputFilterInterface $inputFilter){
throw new \Exception("Not used");
}
public function getInputFilter(){
if (!$this->inputFilter) {
$dataTopic = $this->topicData;
$dataSubTopic = $this->subTopicData;
$inputFilter = new InputFilter();
$factory = new InputFactory();
$inputFilter->add($factory->createInput(array(
'name' => 'topic_name',
'required' => true,
'filters' => array(
array('name' => 'StripTags'),
array('name' => 'StringTrim'),
),
'validators' => array(
array(
'name' => 'Callback',
'options' => array(
'messages' => array(
\Zend\Validator\Callback::INVALID_VALUE => 'Seletec value is not valid',
),
"callback" => function() use ($dataTopic) {
$strip = new \Zend\I18n\Validator\IsInt();
foreach($dataTopic as $key => $tag) {
$tag = $strip->isValid((int)$tag);
$dataTopic[$key] = $tag;
}
return $dataTopic;
},
),
),
),
)));
$inputFilter->add($factory->createInput(array(
'name' => 'sub_topic_name',
'required' => true,
'filters' => array(
array('name' => 'StripTags'),
array('name' => 'StringTrim'),
),
'validators' => array(
array(
'name' => 'Callback',
'options' => array(
'messages' => array(
\Zend\Validator\Callback::INVALID_VALUE => 'Invalid Sub Topic Name',
),
"callback" => function() use ($dataSubTopic) {
$strip = new \Zend\Validator\StringLength(array('encoding' => 'UTF-8','min' => 1,'max' => 100));
foreach($dataSubTopic as $key => $tag) {
$tag = $strip->isValid($tag);
$dataSubTopic[$key] = $tag;
}
return $dataSubTopic;
},
),
),
),
)));
$this->inputFilter = $inputFilter;
}
return $this->inputFilter;
}
}
In the above line of code the value of
$data['data']['topic_name']=array('0' => 1,'1' => 1)
and $data['data']['sub_topic_name']=array('0'=>'Testing','1'=>'Testing1');
and i am calling it
$form = new AddSubTopicForm();
$logFilterForm = new AddSubTopicFilterForm();
$form->setInputFilter($logFilterForm->getInputFilter());
$form->setData($request->getPost());
Below is the of the form class
<?php
namespace Tutorials\Form;
use Zend\Form\Element;
use Zend\Form\Form;
class AddSubTopicForm extends Form {
public function __construct($data = array()){
parent::__construct('AddSubTopic');
$this->setAttribute('class', 'form-horizontal');
$this->setAttribute('novalidate', 'novalidate');
$this->add(array(
'type' => 'Zend\Form\Element\Select',
'name' => 'topic_name[]',
'attributes' => array(
'id' => 'topic_name',
'class' => 'form-control',
),
'options' => array(
'label' => ' Topic Name',
'empty_option'=>'---None--- ',
'value_options' => array(
'1' => 'PHP'
),
),
));
$this->add(array(
'name' => 'sub_topic_name[]',
'attributes' => array(
'type' => 'text',
'id' => 'sub_topic_name',
'class' => 'form-control',
'value' => ''
),
'options' => array(
'label' => ' Sub Topic Name',
),
));
$this->add(array(
'name' => 'id',
'attributes' => array(
'type' => 'hidden',
'id' => 'id'
)
));
$button = new Element('add_more_sub_topic');
$button->setValue('+AddMore');
$button->setAttributes(array(
'type' => 'button',
'id'=>'add_more',
'class'=>'btn btn-info'
));
$save = new Element('save');
$save->setValue('Save');
$save->setAttributes(array(
'type' => 'submit',
'id'=>'save',
'class'=>'btn btn-info'
));
$reset = new Element('reset');
$reset->setValue('Reset');
$reset->setAttributes(array(
'type' => 'reset',
'id'=>'reset',
'class'=>'btn'
));
$this->add($button);
$this->add($save);
$this->add($reset);
}//end of function_construct.
}//end of registration form class.
But it is not calling the filter callback function rather give me an error on first first form field that 'value is required ,can't be empty'
I don't why it is not validating data.Suggest me what where i am wrong and how can i overcome from this problem. Any help would be appreciated. Than.x
I have a simple form class setup along with a filter. After submitting the form, if there's a validation error, the validation/filter works and I can dump the filtered values, but the form does not display the cleaned data. In particular, I am testing with StringTrim and StripTags. I can see the trimmed value, but the final form output still shows the original value submitted. How do I use the validated values instead when the form is repopulated?
An example:
Form data submitted string " asdf ".
Dumping form data, $regform->getData() : "asdf"
The above is expected, but the output in the view still shows the spaces: " asdf ".
I appreciate any input. Code is below. Thank you!
Controller code:
public function indexAction ()
{
$this->layout()->pageTitle = "Account Registration";
$regform = new RegForm($data=null);
if($this->request->isPost()){
$data = $this->post;
$regform->setData($data);
$ufilter = new RegFilter();
$regform->setInputFilter($ufilter->getInputFilter());
if($regform->isValid()){
$this->view->result = "ok";
}
else {
$this->view->result = "Not good";
}
var_dump($regform->getData());
}
$this->view->regform = $regform;
return $this->view;
}
RegForm.php
<?php
namespace GWMvc\Form;
use Zend\Form\Form;
use Zend\Form\Element;
use Zend\Form\Fieldset;
use Zend\InputFilter\InputFilterProviderInterface;
use Zend\Session\Container;
class RegForm extends Form
{
public function __construct($data = null, $args = array())
{
parent::__construct('reg-form');
$this->setAttribute('class', 'form form-inline');
$this->setAttribute('role', 'form');
$this->setAttribute('method', 'post');
$this->setAttribute('action','/app/registration/index');
$this->add(array(
'name' => 'firstname',
'type' => 'Zend\Form\Element\Text',
'options' => array(
'label' => 'First Name:',
),
'attributes' => array('id' => 'firstname', 'type' => 'text',
'class' => 'regformitem regtextfield')));
$this->add(array(
'name' => 'lastname',
'type' => 'Zend\Form\Element\Text',
'options' => array(
'label' => 'Last Name:'
),
'attributes' => array('id' => 'lastname', 'type' => 'text',
'required' => true,'class' => 'regformitem regtextfield')));
$this->add(array(
'type' => 'Zend\Form\Element\Csrf',
'name' => 'csrf',
'options' => array(
'csrf_options' => array(
'timeout' => 600
)
)
));
$this->add(array(
'name' => 'submit',
'attributes' => array(
'type' => 'submit',
'value' => 'Submit',
'class' => 'btn btn-default',
),
));
}
}
RegFilter.php
<?php
namespace GWMvc\Form;
use Zend\InputFilter\Factory as InputFactory;
use Zend\InputFilter\InputFilter;
use Zend\InputFilter\InputFilterAwareInterface;
use Zend\InputFilter\InputFilterInterface;
class RegFilter implements InputFilterAwareInterface
{
public $username;
public $password;
protected $inputFilter;
public function setInputFilter(InputFilterInterface $inputFilter)
{
throw new \Exception("Not used");
}
public function getInputFilter()
{
if (!$this->inputFilter) {
$this->inputFilter = new InputFilter();
$this->factory = new InputFactory();
$this->inputFilter->add($this->factory->createInput(array(
'name' => 'firstname',
'required' => true,
'filters' => array(
array('name' => 'StringTrim'),
array('name' => 'StripTags'),
),
'validators' => array(
array(
'name' => 'StringLength',
'options' => array(
'encoding' => 'UTF-8',
'min' => 1,
'max' => 50,
),
),
),
)));
$this->inputFilter->add($this->factory->createInput(array(
'name' => 'lastname',
'required' => true,
'filters' => array(
array('name' => 'StringTrim'),
),
'validators' => array(
array(
'name' => 'StringLength',
'options' => array(
'encoding' => 'UTF-8',
'min' => 1,
'max' => 50,
),
),
),
)));
}
return $this->inputFilter;
}
}
View Script:
<?php
$form = &$this->regform;
$form->prepare();
echo $this->form()->openTag($form);
echo $this->formElement($form->get('csrf'));?>
<div class="form" gwc="regitem">
<?php echo $this->formRow($form->get('firstname')); ?>
</div>
<div class="form" gwc="regitem">
<?php echo $this->formRow($form->get('lastname')); ?>
</div>
EDIT (SOLUTION)
As per the accepted answer below, it was this easy. Here's what I added.
$valid = $regform->isValid();
$regform->setData($regform->getData());
if($valid){
$this->view->result = "ok";
} else {
// not ok, show form again
}
I guess you have to do it manually:
if($regform->isValid()){
$regform->setData ($regform->getData ())->isValid ();
$this->view->result = "ok";
}
I am developing a project with ZF2 and Doctrine. I am attempting to use Doctrine Hydrator in the form creation as shown in this tutorial. In this method, an ObjectManager object is created in the controller and passed to the new form when it is instantiated. Passing the ObjectManager object from the controller to the form creates a problem when I want to use ZF2's FormElementManager because ZF2 requires that I get an instance of the form class through the Zend\Form\FormElementManager instead of directly instantiating it. To work around this requirement, I have created form and fieldset factories based upon the answer to the question How to pass a Doctrine ObjectManager to a form through ZF2 FormElementManager. The method presented in the answer to the question works for typical fieldset elements, but I need to determine how to include a collection element. The tutorial uses the ObjectManager object in the collection element in the parent fieldset, and I need to figure out how to add the collection using a factory.
TagFieldset from the tutorial that I am trying to emulate:
namespace Application\Form;
use Application\Entity\Tag;
use Doctrine\Common\Persistence\ObjectManager;
use DoctrineModule\Stdlib\Hydrator\DoctrineObject as DoctrineHydrator;
use Zend\Form\Fieldset;
use Zend\InputFilter\InputFilterProviderInterface;
class TagFieldset extends Fieldset implements InputFilterProviderInterface
{
public function __construct(ObjectManager $objectManager)
{
parent::__construct('tag');
$this->setHydrator(new DoctrineHydrator($objectManager))
->setObject(new Tag());
$this->add(array(
'type' => 'Zend\Form\Element\Hidden',
'name' => 'id'
));
$this->add(array(
'type' => 'Zend\Form\Element\Text',
'name' => 'name',
'options' => array(
'label' => 'Tag'
)
));
}
public function getInputFilterSpecification()
{
return array(
'id' => array(
'required' => false
),
'name' => array(
'required' => true
)
);
}
}
new TagFieldsetFactory:
namespace Application\Form;
use Zend\Form\Fieldset;
use Application\Entity\Tag;
class TagFieldsetFactory
{
public function __invoke($formElementManager, $name, $requestedName)
{
$serviceManager = $formElementManager->getServiceLocator();
$hydrator = $serviceManager->get('HydratorManager')->get('DoctrineEntityHydrator');
$fieldset = new Fieldset('tags');
$fieldset->setHydrator($hydrator);
$fieldset->setObject(new Tag);
//... add fieldset elements.
$fieldset->add(['...']);
//...
return $fieldset;
}
}
BlogPostFieldset from the tutorial that I am trying to emulate:
namespace Application\Form;
use Application\Entity\BlogPost;
use Doctrine\Common\Persistence\ObjectManager;
use DoctrineModule\Stdlib\Hydrator\DoctrineObject as DoctrineHydrator;
use Zend\Form\Fieldset;
use Zend\InputFilter\InputFilterProviderInterface;
class BlogPostFieldset extends Fieldset implements InputFilterProviderInterface
{
public function __construct(ObjectManager $objectManager)
{
parent::__construct('blog-post');
$this->setHydrator(new DoctrineHydrator($objectManager))
->setObject(new BlogPost());
$this->add(array(
'type' => 'Zend\Form\Element\Text',
'name' => 'title'
));
$tagFieldset = new TagFieldset($objectManager);
$this->add(array(
'type' => 'Zend\Form\Element\Collection',
'name' => 'tags',
'options' => array(
'count' => 2,
'target_element' => $tagFieldset
)
));
}
public function getInputFilterSpecification()
{
return array(
'title' => array(
'required' => true
),
);
}
}
new BlogPostFieldsetFactory:
namespace Application\Form;
use Zend\Form\Fieldset;
use Application\Entity\BlogPost;
class BlogPostFieldsetFactory
{
public function __invoke($formElementManager, $name, $requestedName)
{
$serviceManager = $formElementManager->getServiceLocator();
$hydrator = $serviceManager->get('HydratorManager')->get('DoctrineEntityHydrator');
$fieldset = new Fieldset('blog_post');
$fieldset->setHydrator($hydrator);
$fieldset->setObject(new BlogPost);
//... add fieldset elements.
$fieldset->add(['...']);
//...
return $fieldset;
}
}
in module.config.php:
'form_elements' => [
'factories' => [
'UpdateBlogPostForm' => 'Application\Form\UpdateBlogPostFormFactory',
'BlogPostFieldset' => 'Application\Form\BlogPostFieldsetFactory',
'TagFieldset' => 'Application\Form\TagFieldsetFactory',
],
],
When I add the fieldset elements In my new BlogPostFieldsetFactory I replace this code from the original fieldset:
$this->add(array(
'type' => 'Zend\Form\Element\Text',
'name' => 'title'
));
with this:
$fieldset->add(array(
'type' => 'Zend\Form\Element\Text',
'name' => 'title'
));
How do I replace the collection element from the original fieldset:
$tagFieldset = new TagFieldset($objectManager);
$this->add(array(
'type' => 'Zend\Form\Element\Collection',
'name' => 'tags',
'options' => array(
'count' => 2,
'target_element' => $tagFieldset
)
));
maybe i'm getting your question wrong.... but if you replaced this
$this->add(array(
'type' => 'Zend\Form\Element\Text',
'name' => 'title'
));
whith this:
$fieldset->add(array(
'type' => 'Zend\Form\Element\Text',
'name' => 'title'
));
then you probably can replace this:
$tagFieldset = new TagFieldset($objectManager);
$this->add(array(
'type' => 'Zend\Form\Element\Collection',
'name' => 'tags',
'options' => array(
'count' => 2,
'target_element' => $tagFieldset
)
));
with this:
$tagFieldset = new TagFieldset($objectManager);
$fieldset->add(array(
'type' => 'Zend\Form\Element\Collection',
'name' => 'tags',
'options' => array(
'count' => 2,
'target_element' => $tagFieldset
)
));
now, if you cant pass the $objectManger to the form... well if you look at the code you have this thing available $serviceManager, that thing looks like a DI container, im sure you can get the $objectManager instance from there, and if is not available, you can probably put an instance of it inside.
So de final code probably ending looks like this:
$objectManager = $serviceManager->get('DoctrineObjectManager') //or something like this
$tagFieldset = new TagFieldset($objectManager);
$fieldset->add(array(
'type' => 'Zend\Form\Element\Collection',
'name' => 'tags',
'options' => array(
'count' => 2,
'target_element' => $tagFieldset
)
));
I'm in the process of creating a form that let's the user schedule an event at a specified date, time and timezone. I want to combine the input of those three form fields and store them in one datetime column in the database. Based on the input I want to convert the specified date and time to UTC.
However I'm not completely sure how to write the form code for this. I was writing a Fieldset class extending Fieldset and adding the three fields to this fieldset:
<?php
namespace Application\Form\Fieldset;
use Zend\Form\Fieldset;
use Zend\InputFilter\InputFilterInterface;
use Zend\InputFilter\InputFilterProviderInterface;
use Zend\Stdlib\Hydrator\ClassMethods;
class SendDateFieldset extends Fieldset implements InputFilterProviderInterface
{
public function __construct()
{
parent::__construct('senddate');
$this->add(array(
'name' => 'date',
'type' => 'Text',
'options' => array(
'label' => 'Date to send:',
)
)
);
$this->add(array(
'name' => 'time',
'type' => 'Text',
'options' => array(
'label' => 'Time to send:',
)
)
);
$this->add(array(
'name' => 'timezone',
'type' => 'Select',
'options' => array(
'label' => "Recipient's timezone",
'value_options' => array(
-12 => '(GMT-12:00) International Date Line West',
-11 => '(GMT-11:00) Midway Island, Samoa',
-10 => '(GMT-10:00) Hawaii',
),
),
)
);
}
public function getInputFilterSpecification()
{
return array(
'date' => array(
'required' => true,
'filters' => array(
array('name' => 'StringTrim'),
),
'validators' => array(
array(
'name' => 'Date',
'break_chain_on_failure' => true,
'options' => array(
'message' => 'Invalid date'
),
),
),
),
'time' => array(
'required' => true,
'filters' => array(
array('name' => 'StringTrim'),
),
),
'timezone' => array(
'required' => true,
),
);
}
}
I then add this fieldset to my form like so:
<?php
namespace Application\Form;
use Zend\Form\Form;
class Order extends Form
{
public function __construct()
{
parent::__construct("new-order");
$this->setAttribute('action', '/order');
$this->setAttribute('method', 'post');
$this->add(
array(
'type' => 'Application\Form\Fieldset\SendDateFieldset',
'options' => array(
'use_as_base_fieldset' => false
),
)
);
}
}
Of course I will add other fieldsets to the form, the base fieldset for the order information itself and another fieldset with recipient info.
I have two questions about this:
What would be the most elegant way to handle the three fields and
store them as 1 datetime (converted to UTC) in the database? I have
an Order service object too that will be responsible for handling a
new order, so I could take care of it in the method responsible for
handling a new order in that service class or is there a better way?
I only posted a small snippet of the list of timezones in the
SendDate fieldset. Is there a cleaner way to do render this list?
Okay, so as promised I'll share my solution to this problem. Hopefully it will help someone else in the future.
I ended up using the SendDateFieldset which I initially had already.
Application\Form\Fieldset\SendDateFieldset:
<?php
namespace Application\Form\Fieldset;
use Application\Hydrator\SendDate as SendDateHydrator;
use Zend\Form\Fieldset;
use Zend\InputFilter\InputFilterInterface;
use Zend\InputFilter\InputFilterProviderInterface;
class SendDateFieldset extends Fieldset implements InputFilterProviderInterface
{
public function __construct()
{
parent::__construct('senddate');
$this->setHydrator(new SendDateHydrator());
$this->setObject(new \DateTime());
$this->add(array(
'name' => 'date',
'type' => 'Text',
'options' => array(
'label' => 'Date to send:',
)
)
);
$this->add(array(
'name' => 'time',
'type' => 'Text',
'options' => array(
'label' => 'Time to send:',
)
)
);
$this->add(array(
'name' => 'timezone',
'type' => 'Select',
'options' => array(
'label' => "Recipient's timezone",
'value_options' => array(
// The list of timezones is being populated by the OrderFormFactory
),
),
)
);
}
public function getInputFilterSpecification()
{
return array(
'date' => array(
'required' => true,
'filters' => array(
array('name' => 'StringTrim'),
),
'validators' => array(
array(
'name' => 'Date',
'break_chain_on_failure' => true,
'options' => array(
'message' => 'Invalid date'
),
),
),
),
'time' => array(
'required' => true,
'filters' => array(
array('name' => 'StringTrim'),
),
'validators' => array(
array(
'name' => 'Callback',
'options' => array(
'callback' => function($value, $context)
{
// #todo: check if date and time is in the future
return true;
}
),
),
),
),
'timezone' => array(
'required' => true,
),
);
}
}
As you can see in this fieldset I now use a plain DateTime object as entity. To populate the DateTime object I use a custom hydrator for this fieldset: SendDateHydrator, which looks like this:
<?php
namespace Application\Hydrator;
use Zend\Stdlib\Hydrator\AbstractHydrator;
use DateTime;
use DateTimeZone;
class SendDate extends AbstractHydrator
{
public function __construct($underscoreSeparatedKeys = true)
{
parent::__construct();
}
/**
* Extract values from an object
*
* #param object $object
* #return array
* #throws Exception\BadMethodCallException for a non-object $object
*/
public function extract($object)
{
throw new Exception\BadMethodCallException(sprintf(
'%s is not implemented yet)', __METHOD__
));
}
/**
* Hydrate data into DateTime object
*
* #param array $data
* #param object $object
* #return object
* #throws Exception\BadMethodCallException for a non-object $object
*/
public function hydrate(array $data, $object)
{
if (!$object instanceof DateTime)
{
throw new Exception\BadMethodCallException(sprintf(
'%s expects the provided $object to be a DateTime object)', __METHOD__
));
}
$object = null;
$object = new DateTime();
if (array_key_exists('date', $data) && array_key_exists('time', $data) && array_key_exists('timezone', $data))
{
$object = new DateTime($data['date'] . ' ' . $data['time'], new DateTimeZone($data['timezone']));
}
else
{
throw new Exception\BadMethodCallException(sprintf(
'%s expects the provided $data to contain a date, time and timezone)', __METHOD__
));
}
return $object;
}
}
The hydrate method takes care of creating the DateTime object using the timezone specified by the user using a selectbox.
To generate the select with timezones in the form I made a small service which uses DateTimeZone to generate a list of timezones and formats them nicely. The end result is an associative array that can be passed to the value options of the select. The keys of this array are official timezone identifiers that DateTimeZone can handle. I pass this list in the factory class responsible for creating the form where I use this selectbox:
Application\Factory\OrderFormFactory:
<?php
namespace Application\Factory;
use Application\Service\TimezoneService;
use Zend\ServiceManager\FactoryInterface;
use Zend\ServiceManager\ServiceLocatorInterface;
use Application\Form\Order as OrderForm;
class OrderFormFactory implements FactoryInterface
{
public function createService(ServiceLocatorInterface $serviceLocator)
{
$orderForm = new OrderForm();
/* #var $timezoneSvc TimezoneService */
$timezoneSvc = $serviceLocator->get('Application\Service\TimezoneService');
// Set list of timezones in SendDate fieldset
$orderForm->get('order')->get('senddate')->get('timezone')->setValueOptions(
$timezoneSvc->getListOfTimezones()
);
return $orderForm;
}
}
The generated fieldset in the form looks like this:
When saving the order the orderservice converts the DateTime to a UTC time before storing it in the database.
I try to validate with the form but I cant get error messages.
//this is my code:
$form = new TestForm();
$form->setInputFilter(new TestFilter());
$data = array('id'=>'','email'=>'myemail#myemail.com');
$form->setData($data);
if($form->isValid()){
echo 'ok';
} else {
echo 'not ok <br/>';
$messagesForm = $form->getMessages();
$filter=$form->getInputFilter();
$messagesFilter=$filter->getMessages();
var_dump($messagesForm);
var_dump($messagesFilter);
}
/////////////////
Output
not ok
//messagesForm
array
empty
//MessagesFilter
array
'id' =>
array
'isEmpty' => string 'Value is required and can't be empty' (length=36)
_
How is possible? The filter is ok, but I can't get error messages from the form
Could be a bug or I made something wrong?
FULL code:
TestFilter:
_
<?php
namespace mvc\filter;
use Zend\InputFilter\InputFilter;
use Zend\InputFilter\Factory as InputFactory;
class TestFilter extends InputFilter
{
public function __construct()
{
$factory = new InputFactory();
$this->add($factory->createInput(array('name'=>'id','required'=>true)));
$this->add($factory->createInput(array('name'=>'email','required'=>true)));
}
}
?>
_
TestForm
_
namespace mvc\form;
use Zend\InputFilter\Factory;
use Zend\Form\Element;
use Zend\Form\Form;
class TestForm extends Form
{
public function prepareElements()
{
$this->add(array(
'name' => 'id',
'attributes' => array(
'type' => 'text',
'label' => 'Your name',
),
));
$this->add(array(
'name' => 'email',
'attributes' => array(
'type' => 'email',
'label' => 'Your email address',
),
));
}
}
?>
_
I have not worked with ZF2 yet but try to add validators to your elements:
use Zend\Validator;
$this->add(array(
'name' => 'id',
'attributes' => array(
'type' => 'text',
'label' => 'Your name',
),
'validator' => new StringLength(array('max'=>20))
));
}
you must specify 'validators', example of a getInputFilter:
use
Zend\InputFilter\InputFilter,
Zend\InputFilter\Factory as InputFactory,
Zend\InputFilter\InputFilterAwareInterface,
Zend\InputFilter\InputFilterInterface;
class User implements InputFilterAwareInterface
{
public function getInputFilter()
{
if (!$this->inputFilter) {
$inputFilter = new InputFilter();
$factory = new InputFactory();
$inputFilter->add($factory->createInput(array(
'name' => 'email',
'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;
}
You may do it this way by retrieving input filter from your model and then setting it to a form:
...
$form = new ItemForm();
$form->setInputFilter($user->getInputFilter());
$form->setData($params);
if ($form->isValid()) {
...
}
...