Not working: FileUpload validation with ZF2 - php

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.

Related

cannot pass data from form to model zend 2.3

I am trying to insert data into seviral tables using tablegateway. I am getting the following error.
Fatal error: Call to a member function saveStudent() on a non-object in C:\xampp\htdocs\disability\module\Admin\src\Admin\Controller\AdminController.php on line 48
I tryed to implement the solution given here Zend\Form: Call to a member function insert() on a non-object in Zend/Form/Fieldset.php
But nothing changed error is the same. Here is my form's code
<?php
namespace Admin\Form;
use Zend\Form\Element;
use Zend\Form\Form;
class AddstudentForm extends Form
{
public function __construct($name = null)
{
// we want to ignore the name passed
// parent::__construct('addstudent');
parent::__construct('AddstudentForm');
$this->add(array(
'name' => 'fio',
'type' => 'Text',
'options' => array(
'label' => 'Фио',
),
));
$this->add(array(
'name' => 'gender',
'type' => 'Zend\Form\Element\Radio',
'options' => array(
'label' => 'Пол',
'value_options' => array(
'0' => 'М',
'1' => 'Ж',
),
),
));
$this->add(array(
'name' => 'birthdate',
'type' => 'Text',
'options' => array(
'label' => 'Дата рождения',
),
));
$this->add(array(
'name' => 'edge',
'type' => 'Text',
'options' => array(
'label' => 'Возраст',
),
));
$this->add(array(
'name' => 'university',
'type' => 'Text',
'options' => array(
'label' => 'Учебное заведение',
),
));
$this->add(array(
'name' => 'group',
'type' => 'Text',
'options' => array(
'label' => 'Группа/класс',
),
));
$this->add(array(
'name' => 'department',
'type' => 'Text',
'options' => array(
'label' => 'Факультет',
),
));
$this->add(array(
'name' => 'grate',
'type' => 'Zend\Form\Element\Radio',
'options' => array(
'label' => 'Курс',
'value_options' => array(
'0' => '1',
'1' => '2',
'2' => '3',
'3' => '4',
'4' => '5',
'5' => '6',
),
),
));
$this->add(array(
'name' => 'enterence',
'type' => 'Text',
'options' => array(
'label' => 'Год поступления',
),
));
$this->add(array(
'name' => 'financesource',
'type' => 'Zend\Form\Element\Radio',
'options' => array(
'label' => 'Источник финансирования',
'value_options' => array(
'0' => 'Бютжет',
'1' => 'Контракт',
),
),
));
$this->add(array(
'name' => 'studyform',
'type' => 'Zend\Form\Element\Radio',
'options' => array(
'label' => 'Форма обучения',
'value_options' => array(
'0' => 'Дневная',
'1' => 'Заочная',
),
),
));
$this->add(array(
'name' => 'homeaddress',
'type' => 'Text',
'options' => array(
'label' => 'Домашний адрес',
),
));
$this->add(array(
'name' => 'actualaddress',
'type' => 'Text',
'options' => array(
'label' => 'Фактический адрес',
),
));
$this->add(array(
'name' => 'phone',
'type' => 'Text',
'options' => array(
'label' => 'Телефон',
),
));
$this->add(array(
'name' => 'workplace',
'type' => 'Text',
'options' => array(
'label' => 'Место работы',
),
));
$this->add(array(
'name' => 'services',
'type' => 'Zend\Form\Element\Textarea',
'options' => array(
'label' => 'Услуги',
),
));
$this->add(array(
'name' => 'submit',
'type' => 'Submit',
'attributes' => array(
'value' => 'Сохранить',
'id' => 'submitbutton',
),
));
}
}
and controller:
<?php
/**
* Zend Framework (http://framework.zend.com/)
*
* #link http://github.com/zendframework/Admin for the canonical source repository
* #copyright Copyright (c) 2005-2014 Zend Technologies USA Inc. (http://www.zend.com)
* #license http://framework.zend.com/license/new-bsd New BSD License
*/
namespace Admin\Controller;
use Zend\Mvc\Controller\AbstractActionController;
use Zend\View\Model\ViewModel;
use Admin\Model\Admin;
use Admin\Form\AddstudentForm;
class AdminController extends AbstractActionController
{
protected $StudentTable;
public function indexAction()
{
return array();
}
public function getStudentTable()
{
if (!$this->StudentTable) {
$sm = $this->getServiceLocator();
$this->studentTable = $sm->get('Admin\Model\StudentTable');
}
return $this->StudentTable;
}
public function addstudentAction()
{
$form = new AddstudentForm();
// $form->get('submit')->setValue('Сохранить');
$request = $this->getRequest();
if ($request->isPost()) {
$admin = new Admin();
$form->setInputFilter($admin->getInputFilter());
$form->setData($request->getPost());
if ($form->isValid()) {
$admin->exchangeArray($form->getData());
$this->getStudentTable()->saveStudent($admin);
// Redirect to list of albums
// return $this->redirect()->toRoute('admin');
}
}
return array('form' => $form);
// return array();
}
public function fooAction()
{
// This shows the :controller and :action parameters in default route
// are working when you browse to /admin/admin/foo
return array();
}
}
What could be wrong with that. Or what info do you need?
You have a typo in your getStudenTable() method and therefore $this->getStudentTable() returns null.
$this->studentTable = $sm->get('Admin\Model\StudentTable');
should be
$this->StudentTable = $sm->get('Admin\Model\StudentTable');

ZF 2.3 displaying form in different modules

I'm trying to create a simple application with Zend Framework 2 and now stacked at the point of adding comments form.
I have two modules "Book" and "Comment". I want to show a form for adding comments that is disposed in module "Comment" from "Books" module controller.
The problem appears when I'm trying to open forms tag.
I'm having this error : " Fatal error: Call to undefined method Comment\Form\CommentForm::openTag()".
I tried to check $this->addComment - with var_dump and everything looks great.
Can anybody help me to solve this problem ?
<div class="row">
<div class="col-xs-12 commentBlock">
<?php
if($this->addComment){
$this->addComment->prepare();
$commentFieldset = $this->addComment->get('comment');
print $this->addComment()->openTag($this->addComment);
}
?>
</div>
</div>
Here is 'Comment' module files :
Comment\Form\CommentFieldset
<?php
namespace Comment\Form;
use Comment\Entity\Comment;
use Zend\Form\Fieldset;
use Zend\InputFilter\InputFilterProviderInterface;
use Zend\Stdlib\Hydrator\ClassMethods as ClassMethodsHydrator;
class CommentFieldset extends Fieldset implements InputFilterProviderInterface
{
public function __construct()
{
parent::__construct('comment');
$this->add(
array(
'name' => 'commentTitle',
'attributes' => array(
// 'required' => 'required',
'class' => 'form-controll',
'placeholder' => 'Введите заголовок комментария'
),
'options' => array(
'label' => 'Заголовок комментария',
'label_attributes' => array(
'class' => 'text-center col-sm-3 control-label',
),
),
)
);
$this->add(
array(
'name' => 'commentText',
'type' => 'Zend\Form\Element\Textarea',
'attributes' => array(
'required' => 'required',
'class' => 'form=-controll',
'palceholder' => 'Введите текст комментария',
),
'options' => array(
'label' => 'Текст комментария',
'label_attributes' => array(
'class' => 'text-center col-sm-3 control-label',
),
),
)
);
$this->add(
array(
'name' => 'commentType',
'type' => 'Zend\Form\Element\Radio',
'attributes' => array(
'required' => 'required',
),
'options' => array(
'label' => 'Тип комментария',
'label_attributes' => array(
'class' => 'text-center col-sm-3 control-label',
),
'value_options' => array(
'positive' => 'postive',
'neutral' => 'neutral',
'negative' => 'negative',
),
),
)
);
}
public function getInputFilterSpecification()
{
return array(
'commentTitle' => array(
'required' => FALSE,
'filters' => array(
array(
'name' => 'Zend\Filter\StripTags',
),
array(
'name' => 'Zend\Filter\HtmlEntities'
),
array(
'name' => 'Zend\Filter\StringTrim',
),
),
'validators' => array(
array(
'name' => 'Zend\Validator\StringLength',
'options' => array(
'min' => 1,
'max' => 250,
),
),
),
),
'commentText' => array(
'required' => TRUE,
'filters' => array(
array(
'name' => 'Zend\Filter\StripTags',
),
array(
'name' => 'Zend\Filter\HtmlEntities'
),
array(
'name' => 'Zend\Filter\StringTrim',
),
),
'validators' => array(
array(
'name' => '\Zend\Validator\StringLength',
'options' => array(
'min' => 1,
'max' => 1000,
),
),
),
),
'commentType' => array(
'required' => true,
'validators' => array(
array(
'name' => 'Zend\Validator\InArray',
'options' => array(
'haystack' => array(
'positive',
'neutral',
'negative',
),
'strict' =>\Zend\Validator\InArray::COMPARE_STRICT,
),
),
),
),
);
}
}
Comment\Form\CommentFieldset
<?php
namespace Comment\Form;
use Zend\Form\Form;
use Zend\InputFilter\InputFilter;
use Zend\Stdlib\Hydrator\ClassMethods as ClassMethodsHydrator;
class CommentForm extends Form
{
public function __construct()
{
parent::__construct('comment');
$this
->setAttribute('method', 'POST')
->setHydrator(new ClassMethodsHydrator())
->setInputFilter(new InputFilter())
;
$this->add(
array(
'type' => 'Comment\Form\CommentFieldset',
'options' => array(
'use_as_base_fieldset' => true,
),
)
);
$this->add(
array(
'name' => 'csrf',
'type' => 'Zend\Form\Element\Csrf',
)
);
$this->add(
array(
'name' => 'captcha',
'type' => 'Zend\Form\Element\Captcha',
'options' => array(
'label' => 'А вы точно-приточно не робот ? ',
'captcha' => new \Zend\Captcha\Figlet(),
'attributes' => array(
'required' => true,
)
),
)
);
$this->add(
array(
'name' => 'submit',
'attributes' => array(
'type' => 'submit',
'value' => 'Добавить комментарий',
'class' => 'bigSubmit btn btn-pink',
),
)
);
$this->setValidationGroup(
array(
'csrf',
'captcha',
'comment' => array(
'commentTitle',
'commentText',
'commentType',
),
)
);
}
}
Comment\View\Helper\DisplayAddCommentForm
<?php
namespace Comment\View\Helper;
use Zend\Form\View\Helper\AbstractHelper;
class DisplayAddCommentForm extends AbstractHelper
{
public function __invoke()
{
return new \Comment\Form\CommentForm();
}
}
Book\Controller\BookController
<?php
namespace Book\Controller;
use Zend\Mvc\Controller\AbstractActionController;
use Zend\View\Model\ViewModel;
use Zend\View\Model\JsonModel;
use Comment\Form\CommentForm;
class BookController extends AbstractActionController
{
protected $bookModel;
protected $commentsModel;
public function showAction()
{
$isbn = $this->params()->fromRoute('num');
$book = $this->bookModel->getU(array($isbn));
$comments = $this->commentsModel->getBookComments(array($isbn));
if($_SESSION['user']){
$commentForm = new CommentForm();
} else {
$commentForm = NULL;
}
return new ViewModel(
array(
'book' => $book,
'comments' => $comments,
'addComment' => $commentForm,
)
);
}
**************
}
openTag() is method from form view helper not from your helper. In your view script change this line : print $this->addComment()->openTag($this->addComment); to this one print $this->form()->openTag($this->addComment);

Argument passed to Zend\Form\Form::setInputFilter() must implement interface InputFilterInterface, null given

Well, greeting everybody, i was just following along the zend framework 2 example code for creating an album management app (http://framework.zend.com/manual/2.0/en/user-guide/forms-and-actions.html) but ran into the following error while testing the "add" functionallity:
Catchable fatal error: Argument 1 passed to
Zend\Form\Form::setInputFilter() must implement interface
Zend\InputFilter\InputFilterInterface, null given.
I have been checking my app code to try and solve this problem but i just simply dont see what's wrong with it, even worst, searching for the error message doesn't yield any results, which is why i'm recurring to your knowledge to try and solve this, here is my code:
SystemController.php
<?php
namespace System\Controller;
use Zend\Mvc\Controller\AbstractActionController;
use Zend\View\Model\ViewModel;
use System\Model\User;
use System\Form\UserRegisterForm;
Class SystemController extends AbstractActionController
{
protected $userTable;
public function indexAction()
{
return new ViewModel(array(
'system' => $this->getUserTable()->fetchAll(),
));
}
public function editAction()
{
}
public function deleteAction()
{
}
public function registerAction()
{
$form = new UserRegisterForm();
$form->get('submit')->setValue('Register');
$request = $this->getRequest();
if ($request->isPost()) {
$user = new User();
$form->setInputFilter($user->getInputFilter());
$form->setData($request->getPost());
if ($form->isValid()) {
$user->exchangeArray($form->getData());
$this->getUserTable()->saveUser($user);
// Redirect to list of albums
return $this->redirect()->toRoute('system');
}
}
return array('form' => $form);
}
public function loginAction()
{
}
public function usersAction()
{
}
public function getUserTable()
{
if (!$this->userTable) {
$sm = $this->getServiceLocator();
$this->userTable = $sm->get('System\Model\UserTable');
}
return $this->userTable;
}
}
The error message point out that the null is being given on the line 45, line 455 corresponds to the following code snippet:
$form->setInputFilter($user->getInputFilter());
From is an instance of my UserRegisterForm class
UserRegisterForm.php
<?php
namespace System\Form;
use Zend\Form\Form;
class UserRegisterForm extends Form
{
public function __construct($name = null)
{
parent::__construct('user');
$this->setAttribute('method', 'post');
$this->add(array(
'name' => 'id',
'attributes' => array(
'type'=>'hidden',
),
));
$this->add(array(
'name' => 'username',
'attributes' => array(
'type' => 'text',
),
'options' => array(
'label' => 'Username',
),
));
$this->add(array(
'name' => 'first_name',
'attributes' => array(
'type' => 'text',
),
'options' => array(
'label' => 'First Name',
),
));
$this->add(array(
'name' => 'last_name',
'attributes' => array(
'type' => 'text',
),
'options' => array(
'label' => 'Last Name',
),
));
$this->add(array(
'name' => 'email',
'attributes' => array(
'type' => 'text',
),
'options' => array(
'label' => 'E-mail',
),
));
$this->add(array(
'name' => 'password',
'attributes' => array(
'type' => 'password',
),
'options' => array(
'label' => 'Password',
),
));
$this->add(array(
'name' => 'type',
'attributes' => array(
'type' => 'text',
),
'options' => array(
'label' => 'Type',
),
));
$this->add(array(
'name' => 'submit',
'attributes' => array(
'type' => 'submit',
'value' => 'Register User',
'id' => 'submitbutton',
),
));
}
}
And user is an instance of my user model
User.php
<?php
namespace System\Model;
use Zend\InputFilter\Factory as InputFactory;
use Zend\InputFilter\InputFilter;
use Zend\InputFilter\InputFilterAwareInterface;
use Zend\InputFilter\InputFilterInterface;
class User implements InputFilterAwareInterface
{
public $id;
public $first_name;
public $last_name;
public $username;
public $email;
public $password;
public $type;
public function exchangeArray($data)
{
$this->id = (isset($data['id'])) ? $data['id'] : null;
$this->first_name = (isset($data['first_name'])) ? $data['first_name'] : null;
$this->last_name = (isset($data['last_name'])) ? $data['last_name'] : null;
$this->username = (isset($data['username'])) ? $data['username'] : null;
$this->email = (isset($data['email'])) ? $data['email'] : null;
$this->password = (isset($data['password'])) ? $data['password'] : null;
$this->password = (isset($data['type'])) ? $data['type'] : null;
}
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' => 'id',
'required' => true,
'filters' => array(
array('name' => 'Int'),
),
)));
$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' => 3,
'max' => 100,
),
),
),
)));
$inputFilter->add($factory->createInput(array(
'name' => 'first_name',
'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($factory->createInput(array(
'name' => 'last_name',
'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($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' => 10,
'max' => 150,
),
),
),
)));
$inputFilter->add($factory->createInput(array(
'name' => 'password',
'required' => true,
'filters' => array(
array('name' => 'StripTags'),
array('name' => 'StringTrim'),
),
'validators' => array(
array(
'name' => 'StringLength',
'options' => array(
'encoding' => 'UTF-8',
'min' => 6,
'max' => 50,
),
),
),
)));
}
return $this->inputFilter;
}
}
I just don't see what is wrong with the code, for me everything is fine, this error is showing up when i try and submit a from from the register view. but i just don't understand why this is happening.
register.phtml
<?php
$title = 'Register a new user';
$this->headTitle($title);
?>
<h1><?php echo $this->escapeHtml($title); ?></h1>
<?php
$form = $this->form;
$form->setAttribute('action', $this->url('system', array('action' => 'register')));
$form->prepare();
/*
echo $this->formCollection($form);
*/
echo $this->form()->openTag($form);
echo $this->formHidden($form->get('id'));
echo $this->formRow($form->get('username'));
echo $this->formRow($form->get('first_name'));
echo $this->formRow($form->get('last_name'));
echo $this->formRow($form->get('email'));
echo $this->formRow($form->get('password'));
echo $this->formRow($form->get('type'));
echo $this->formSubmit($form->get('submit'));
echo $this->form()->closeTag();
Any help is appreciated, 'cause i'm just about to give up.
The getInputFiler() method in your user model returns $this->inputFilter, but that property is never set. I think you're missing a $this->inputFilter = $inputFilter assignment towards the end of that function.
In your User.php change
return $this->inputFilter;
to
return $inputFilter
Your $this->inputFilter is always null. As Tim Fountain has mentioned it, it is never set.
Answer is given above
..but nevertheless I suggest to create a separate InputFilter class and do not define it within your model. If you have more than 1 model object, each model instance will have an InputFilter definition inside.

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

zend framework 2 with doctrine 2 $form->getData() in controller not returning all fields set using $form->setData()

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.

Categories