ZF2 form validation is empty validations always fails - php

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 ._.'

Related

zend form validation is not working using callback validator using zend framework2

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

How to pass data in ZF2 from Controller to Form using serviceLocator

I need to pass data from a Controller to a Fieldset, how do I do this if I use the serviceLocator and FactoryInterface to get my forms? Is it even possible?
Currently my files look like this:
Controller
$eventID = $id;
$matuserID = $this->zfcUserAuthentication()->getIdentity()->getId();
// DATA I would like to pass to the form
$dataDB = array('eventid' => $eventID, 'matuserid' => $matuserID);
// Get Form
$form = $this->getServiceLocator()->get('mat_multimail_createform');
CreateFormFactory
public function createService(ServiceLocatorInterface $sm)
{
$multimailFieldset = $sm->get('mat_multimail_fieldset');
$form = new MultiMailCreateForm($multimailFieldset);
// Set the hydrator
$form->setHydrator(new DoctrineHydrator($sm->get('Doctrine\ORM\EntityManager')));
return $form;
}
CreateForm
public function __construct(FieldsetInterface $multimailFieldset)
{
parent::__construct('create-multimail');
//set the base fieldset
$multimailFieldset->setUseAsBaseFieldset(true);
$this->add($multimailFieldset);
$this->add(array(
'name' => 'submit',
'attributes' => array(
'type' => 'submit',
'value' => 'Speichern',
'class' => 'btn btn-primary',
'id' => 'submultimail'
)
));
}
CreateFieldsetFactory
public function createService(ServiceLocatorInterface $sm)
{
$om = $sm->get('Doctrine\ORM\EntityManager');
$form = new MultiMailFieldset($om, $options);
// Set the hydrator
$form->setHydrator(new DoctrineHydrator($om));
$form->setObject(new Event());
return $form;
}
Fieldset
public function __construct(ObjectManager $om, $options = array())
{
parent::__construct('multimail');
$this->add(array(
'type' => 'Zend\Form\Element\Hidden',
'name' => 'id'
));
$this->add(array(
'type' => 'Zend\Form\Element\Hidden',
'name' => 'eventid'
));
$this->add(array(
'type' => 'DoctrineModule\Form\Element\ObjectSelect',
'name' => 'extadressen',
'attributes' => array(
'class' => 'form-control',
'id' => 'singleExtSel',
'multiple' => 'multiple',
),
'options' => array(
'object_manager' => $om,
'target_class' => 'Mat\Entity\AdressenExt',
'property' => 'email',
'is_method' => true,
'find_method' => array(
'name' => 'getExtAdressen',
'params' => array(
'criteria' => array('userid' => $options['matuserid'], 'eventid' => $options['eventid']),
),
),
),
));
Or do I have to change the controller to something like this:
$options = array('eventid' => 1, 'matuserid' => 2);
$form = new MultiMailFieldset($om, $options);
// Set the hydrator
$form->setHydrator(new DoctrineHydrator($om));
$form->setObject(new Event());
THANKS!
Ok, I figured it out, thanks to this post ZF2 Get params in factory!
I get the params in the factory and pass them on to the fieldset:
FieldsetFactory
public function createService(ServiceLocatorInterface $sm)
{
$om = $sm->get('Doctrine\ORM\EntityManager');
// add user id
$authUser = $sm->get('zfcuser_auth_service');
$authUserId = $authUser->getIdentity()->getId();
// add current eventID to fetch addresses
$router = $sm->get('router');
$request = $sm->get('request');
$routerMatch = $router->match($request);
$eventID = $routerMatch->getParam("id");
$options = array('userid' => $authUserId, 'eventid' => $eventID);
$form = new MultiMailFieldset($om, $options);
// Set the hydrator
$form->setHydrator(new DoctrineHydrator($om));
$form->setObject(new Event());
return $form;
}
Fieldset
public function __construct(ObjectManager $om, $options = array())
{
parent::__construct('multimail');
$this->add(array(
'type' => 'Zend\Form\Element\Hidden',
'name' => 'id'
));
$this->add(array(
'type' => 'Zend\Form\Element\Hidden',
'name' => 'eventid'
));
// add current eventID to fetch addresses
$this->add(array(
'type' => 'DoctrineModule\Form\Element\ObjectSelect',
'name' => 'extadressen',
'attributes' => array(
'class' => 'form-control',
'id' => 'singleExtSel',
'multiple' => 'multiple',
),
'options' => array(
'object_manager' => $om,
'target_class' => 'Mat\Entity\AdressenExt',
'property' => 'email',
'is_method' => true,
'find_method' => array(
'name' => 'getExtAdressen',
'params' => array(
'criteria' => array('userid' => $options['userid'], 'eventid' => $options['eventid']),
),
),
),
)); ...

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).

How to check if an email already registered in form

I am writing a Registration code and i am looking for email uniqueness. If user enters a email that is already registered, the form should thrown error.
I have try both NoRecordExists, and RecordExists. None is working here
I have implemented "Db\NoRecordExists", but it is not working. It is not throwing error nor it is checking email in Db.
My controller is like
$sm = $this->getServiceLocator();
$dbAdapter = $sm->get('Zend\Db\Adapter\Adapter');
if ($request->isPost()) {
#Filter the Input
$form->setInputFilter(new RegisterStepFirstFilter($dbAdapter));
$form->setData($request->getPost());
if (!$form->isValid()) {
#error comes
$this->flashMessenger()->addMessage('Oops an error is occured');
}else{
#No error.Proceed with Registration
}
}
My Registration Filter Class is like
namespace User\Form;
use Zend\InputFilter\InputFilter;
class RegisterStepFirstFilter extends InputFilter
{
private $dbAdapter;
public function __construct($dbAdapter) {
$this->add(array(
'name' => 'user_email',
'required' => true,
'filters' => array(
array('name' => 'StripTags'),
array('name' => 'StringTrim'),
array('name' => 'HtmlEntities'),
),
'validators' => array(
array('name' => 'EmailAddress'),
array('name' => 'StringLength', 'options' => array('encoding' => 'UTF-8', 'min' => 1, 'max' => 200,),
array('name' => 'Db\NoRecordExists', 'options' => array('table' => 'y2m_user','field' => 'user_email', 'adapter' => $dbAdapter),),
),
),
));
}
}}
The Registration form works perfectly with all other Validators. But it is not checking Email uniqueness not it is throwing any error(I have already enable the error)
Any suggestion will be appreciated.
The Issue was because of Type.I forgot to put a Comma after in a filter .Strange, zf2 was not given any error
I have update validator
'validators' => array(
array('name' => 'EmailAddress'),
array('name' => 'StringLength', 'options' => array('encoding' => 'UTF-8', 'min' => 1, 'max' => 200,),),
array('name' => 'Db\NoRecordExists', 'options' => array('table' => 'y2m_user','field' => 'user_email', 'adapter' => $dbAdapter),),
),
You use the wrong validator, you need to use Db\NoRecordExists.

Zend Framework 2 - Building a simple form with Validators

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!
}

Categories