I am trying use zf2 to validate form, but have errors:
An error occurred
An error occurred during execution; please try again later.
Additional information:
Zend\InputFilter\Exception\RuntimeException
File:
C:\xampp\htdocs\ZEND\Users\Users\vendor\ZF2\library\Zend\InputFilter\Factory.php:395
Message:
Invalid validator specification provided; was neither a validator instance nor an array specification
Code:
<?php
namespace Users\Form;
use Zend\InputFilter\InputFilter;
class RegisterFilter extends InputFilter{
public function __construct(){
$this->add(array(
'name' => 'email',
'required' =>true,
'validators' => array(
'name' => 'EmailAddress',
'options' => array(
'domain' => true,
),
),
));
$this->add(array(
'name' => 'user',
'required' => true,
'filters' => array(
array('name' => 'StripTags'),
array('name' => 'StringLength'),
),
'validators' => array(
array(
'options' => array(
'encoding' => 'UTF-8',
'min' => 6,
'max' => 32,
),
),
),
));
}
}
RegisterForm
<?php
namespace Users\Form;
use Zend\Form\Form;
class RegisterForm extends Form {
public function __construct($name = null){
parent::__construct('Register');
$this->setAttribute('method', 'post');
$this->setAttribute('enctype', 'multipart/form-data');
$this->add(array(
'name' => 'user',
'attributes' => array(
'type' => 'text',
'required' => 'required'
),
'options' => array(
'label' => 'UserName',
),
));
$this->add(array(
'name' => 'pwd',
'attributes' => array(
'type' => 'password',
'required' => 'required'
),
'options' => array(
'label' => 'Password',
)
));
$this->add(array(
'name' => 'cpwd',
'attributes' => array(
'type' => 'password',
'required' => 'required'
),
'options' => array(
'label' => 'Comfirm Password',
),
));
$this->add(array(
'name' => 'submit',
'attributes' => array(
'type' => 'submit',
'value' => 'Register',
),
));
$this->add(array(
'name' => 'email',
'attributes' => array(
'type' => 'email',
),
'options' => array(
'label' => 'Email',
),
'attributes' => array(
'required' => 'required',
),
'filters' => array(
array('name' => 'StringTrim')
),
'validators' => array(
array(
'name' => 'EmailAddress',
'options' => array(
'messages' => array(
\Zend\Validator\EmailAddress::INVALID_FORMAT => 'Email Address Format is invalid'
)
)
)
)
));
}
}
RegisterController
<?php
namespace Users\Controller;
use Zend\Mvc\Controller\AbstractActionController;
use Zend\View\Model\ViewModel;
use Users\Form\RegisterForm;
use Users\Form\RegisterFilter;
class RegisterController extends AbstractActionController{
public function indexAction(){
$form = new RegisterForm();
$viewmodel = new ViewModel(array('form' => $form));
return $viewmodel;
}
public function processAction(){
if(!$this->request->isPost()){
return $this->redirect()-> toRoute(NULL,
array( 'controller' => 'register',
'action' => 'index',
));
}
$post = $this->request->getPost();
$form = new RegisterForm();
$inputFilter = new RegisterFilter();
$form->setInputFilter($inputFilter);
$form->setData($post);
if(!$form->isValid()){
$model = new ViewModel(array(
'error' => true,
'form' => $form,
));
$model ->setTemplate('users/register/index');
return $model;
}
return $this->redirect()->toRoute(NULL,array(
'controller' => 'register',
'action' => 'confirm',
));
}
public function confirmAction(){
$viewmodel = new ViewModel();
return $viewmodel;
}
}
index.phtml
<section class = 'register'>
<h2> Register </h2>
<?php if($this -> error): ?>
<p class='error'> have errors </p>
<?php endif ?>
<?php
$form = $this->form;
$form -> prepare();
$form -> setAttribute('action', $this->url(NULL,
array('controller' => 'Register', 'action' => 'process')));
$form -> setAttribute('method','post');
echo $this->form()->openTag($form);
?>
<dl class='zend_form'>
<dt><?php echo $this->formLabel($form -> get('user')) ;?> </dt>
<dd> <?php echo $this->formElement($form->get('user')) ;?>
<?php echo $this->formElementErrors($form->get('user')) ;?>
</dd>
<dt><?php echo $this->formLabel($form -> get('email'));?></dt>
<dd><?php echo $this->formElement($form-> get('email')) ;?>
<?php echo $this->formElementErrors($form -> get('email')) ;?>
</dd>
<dt><?php echo $this->formLabel($form -> get('pwd')) ;?></dt>
<dd><?php echo $this->formElement($form->get('pwd')) ;?>
<?php echo $this->formElementErrors($form->get('pwd')) ;?>
</dd>
<dt><?php echo $this->formLabel($form ->get('cpwd'));?></dt>
<dd><?php echo $this->formElement($form->get('cpwd'));?>
<?php echo $this->formElementErrors($form->get('cpwd'))?>
</dd>
<dd><?php echo $this->formElement($form->get('submit'));?>
<?php echo $this->formElementErrors($form->get('submit'));?>
</dd>
</dl>
<?php echo $this->form()->closeTag()?>
</section>
Your validator structure is wrong.
The validators key is expecting an array of validators. You are supplying the validator name and options directly.
Change this:
this->add(array(
'name' => 'email',
'required' =>true,
'validators' => array(
'name' => 'EmailAddress',
'options' => array(
'domain' => true,
),
),
));
To:
this->add(array(
'name' => 'email',
'required' =>true,
'validators' => array(
array(
'name' => 'EmailAddress',
'options' => array(
'domain' => true,
),
)
//Another validator here ..
),
));
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";
}
Having a registration zend form in view looks like this :
<?php
$form = $this->form;
if(isset($form)) $form->prepare();
$form->setAttribute('action', $this->url(NULL,
array('controller' => 'register', 'action' => 'process')));
echo $this->form()->openTag($form);
?>
<dl class="form-signin">
<dd><?php
echo $this->formElement($form->get('name_reg'));
echo $this->formElementErrors($form->get('name_reg'));
?></dd>
<dd><?php
echo $this->formElement($form->get('email_reg'));
echo $this->formElementErrors($form->get('email_reg'));
?></dd>
<dd><?php
echo $this->formElement($form->get('password_reg'));
echo $this->formElementErrors($form->get('password_reg'));
?></dd>
<dd><?php
echo $this->formElement($form->get('confirm_password_reg'));
echo $this->formElementErrors($form->get('confirm_password_reg'));
?></dd>
<br>
<dd><?php
echo $this->formElement($form->get('send_reg'));
echo $this->formElementErrors($form->get('send_reg'));
?></dd>
<?php echo $this->form()->closeTag() ?>
And RegisterController as following.
<?php
namespace Test\Controller;
use Zend\Mvc\Controller\AbstractActionController;
use Zend\View\Model\ViewModel;
use Zend\Session\Container;
use Test\Form\RegisterForm;
use Test\Form\RegisterFilter;
use Test\Form\LoginFormSm;
use Test\Form\LoginFilter;
use Test\Model\User;
use Test\Model\UserTable;
class RegisterController extends AbstractActionController
{
public function indexAction()
{
$this->layout('layout/register');
$form = new RegisterForm();
$form_sm = new LoginFormSm();
$viewModel = new ViewModel(array(
'form' => $form,
'form_sm' =>$form_sm,
));
return $viewModel;
}
public function processAction()
{
$this->layout('layout/register');
if (!$this->request->isPost()) {
return $this->redirect()->toRoute(NULL,
array( 'controller' => 'index'
)
);
}
$form = $this->getServiceLocator()->get('RegisterForm');
$form->setData($this->request->getPost());
if (!$form->isValid()) {
$model = new ViewModel(array(
'form' => $form,
));
$model->setTemplate('test/register/index');
return $model;
}
// Creating New User
$this->createUser($form->getData());
return $this->redirect()->toRoute(NULL, array (
'controller' => 'auth' ,
));
}
protected function createUser(array $data)
{
$userTable = $this->getServiceLocator()->get('UserTable');
$user = new User();
$user->exchangeArray($data);
$userTable->saveUser($user);
return true;
}
}
Also a RegisterForm where are declared all variables shown in index. Also RegisterFilter as following:
<?php
namespace Test\Form;
use Zend\InputFilter\InputFilter;
class RegisterFilter extends InputFilter
{
public function __construct()
{
$this->add(array(
'name' => 'email_reg',
'required' => true,
'filters' => array(
array(
'name' => 'StripTags',
),
array(
'name' => 'StringTrim',
),
),
'validators' => array(
array(
'name' => 'EmailAddress',
'options' => array(
'domain' => true,
'messages' => array(
\Zend\Validator\EmailAddress::INVALID_FORMAT => 'Email address format is invalid'
),
),
),
array(
'name' => 'AbstractDb',
'options' => array(
'domain' => true,
'messages' => array(
\Zend\Validator\Db\AbstractDb::ERROR_RECORD_FOUND => 'Current Email Already registered'
),
),
),
),
));
$this->add(array(
'name' => 'name_reg',
'required' => true,
'filters' => array(
array(
'name' => 'StripTags',
),
array(
'name' => 'StringTrim',
),
),
'validators' => array(
array(
'name' => 'StringLength',
'options' => array(
'encoding' => 'UTF-8',
'min' => 2,
'max' => 140,
),
),
),
));
$this->add(array(
'name' => 'password_reg',
'required' => true,
'validators' => array(
array(
'name' => 'StringLength',
'options' =>array(
'encoding' => 'UTF-8',
'min' => 6,
'messages' => array(
\Zend\Validator\StringLength::TOO_SHORT => 'Password is too short; it must be at least %min% ' . 'characters'
),
),
),
array(
'name' => 'Regex',
'options' =>array(
'pattern' => '/[A-Z]\d|\d[A-Z]/',
'messages' => array(
\Zend\Validator\Regex::NOT_MATCH => 'Password must contain at least 1 digit and 1 upper-case letter'
),
),
),
),
));
$this->add(array(
'name' => 'confirm_password_reg',
'required' => true,
'validators' => array(
array(
'name' => 'Identical',
'options' => array(
'token' => 'password_reg', // name of first password field
'messages' => array(
\Zend\Validator\Identical::NOT_SAME => "Passwords Doesn't Match"
),
),
),
),
));
}
}
Problem
All i need is to throw a message when somebody tries to register and that e-mail is already registered. Tried with \Zend\Validator\Db\AbstractDb and added following validator to email in RegisterFilter as following
array(
'name' => 'AbstractDb',
'options' => array(
'domain' => true,
'messages' => array(
\Zend\Validator\Db\AbstractDb::ERROR_RECORD_FOUND => 'Current Email Already registered'
),
),
),
But that seems not to work.
Question: Is there a way to implement this validator in RegisterController?
Additional.
I've deleted from RegisterFilert validator and put inside Module.ph
'EmailValidation' => function ($sm) {
$dbAdapter = $sm->get('Zend\Db\Adapter\Adapter');
$validator = new RecordExists(
array(
'table' => 'user',
'field' => 'email',
'adapter' => $dbAdapter
)
);
return $validator;
},
And call it from RegisterController
$validator = $this->getServiceLocator()->get('EmailValidation');
if (!$validator->isValid($email)) {
// email address is invalid; print the reasons
$model = new ViewModel(array(
'error' => $validator->getMessages(),
'form' => $form,
));
$model->setTemplate('test/register/index');
return $model;
}
And when i use print_r inside view to check for it shows.
Array ( [noRecordFound] => No record matching the input was found ).
I want just to echo this 'No record matching the input was found'.
Fixed
Modified in RegisterController as following
$validator = $this->getServiceLocator()->get('EmailValidation');
$email_ch = $this->request->getPost('email_reg');
if (!$validator->isValid($email_ch)) {
// email address is invalid; print the reasons
$model = new ViewModel(array(
'error' => 'Following email is already registered please try another one',
'form' => $form,
));
$model->setTemplate('test/register/index');
return $model;
}
I had compared
if (!$validator->isValid($email_ch))
Before with nothing and that's why i needed to add first
$email_ch = $this->request->getPost('email_reg');
You don't have to do that in your controller, just try this in your RegisterFilter class :
First : Add $sm as parameter of the _construct() method :
public function __construct($sm) {....}
Second: Replace e-mail validation by this one :
$this->add ( array (
'name' => 'email_reg',
'required' => true,
'validators' => array(
array(
'name' => 'Zend\Validator\Db\NoRecordExists',
'options' => array(
'table' => 'user',
'field' => 'email',
'adapter' => $sm->get ( 'Zend\Db\Adapter\Adapter' ),
'messages' => array(
NoRecordExists::ERROR_RECORD_FOUND => 'e-mail address already exists'
),
),
),
),
)
);
When you call the RegisterFilter don't forget to pass the serviceLocator as parameter in your controller :
$form->setInputFilter(new RegisterFilter($this->getServiceLocator()));
Supposing you have this in your global.php File (config\autoload\global.php) :
'service_manager' => array(
'factories' => array(
'Zend\Db\Adapter\Adapter' => 'Zend\Db\Adapter\AdapterServiceFactory',
),
),
To your previous request, ("I want just to echo this 'No record matching the input was found'")
$validator = $this->getServiceLocator()->get('EmailValidation');
$email_ch = $this->request->getPost('email_reg');
if (!$validator->isValid($email_ch)) {
// email address is invalid; print the reasons
foreach ($validator->getMessages() as $message) {
$msg = $message;
}
$model = new ViewModel(array(
'error' => $msg,
'form' => $form,
));
$model->setTemplate('test/register/index');
return $model;
}
I have created a form with nested Collection Customer(Form) -> Categories(Collection/Fieldset) -> Tags(Collection/Fieldset).
It's:
One(Customer) -> Many(Categories)
One(Catogrie) -> Many(Tags)
After bind the customer to the Form it looks like everything is working fine. The Hydrator get the object and the elements where created in Tags.
But in the View the Tag-Elements have no value...
I have checked the Hydrator for typos but everything is fine I copy/paste the index to make sure. When i var_dump the Tags-Collection the objects with value are binded.
I really dont know where the error is, thats why i dont enter some code here I think it would be to much. When you have an idea I can show you the code where you guess the error can be.
Greetings.
Tiega.
EDIT:
Okay I will try to do my best to give you readable code :)
class KontakteController extends AbstractActionController {
public function getKontaktAction()
{
$formManager = $this->serviceLocator->get('FormElementManager');
$kontaktForm = $formManager->get('KontakteManager\Form\KontakteForm');
$id = $this->params()->fromRoute('id');
$kontakt = $this->getKontakte()->getKontakt($id);
if (!$id || !$kontakt) {
return $this->redirect()->toRoute('kontakte', array(
'action' => 'addKontakt'
));
}
$kontakt->initFirmaKommunikation($this->getKommunikation());
$kontakt->initAdressen($this->getAdressen());
$kontakt->initAnsprechpartner($this->getKontakte());
$kontakt->initBankverbindungen($this->getBankverbindung());
$kontakt->initFirmaKategorien($this->getKontakteKategorie());
$kontakt->initPersonKategoiern($this->getKontakteKategorie());
$kontaktForm->bind($kontakt);
return new ViewModel(array(
'kontaktForm' => $kontaktForm,
'geloescht' => $kontakt->geloescht,
'tags' => $this->ladeTags(),
));
}
CustomerFieldset:
class KontakteForm extends Form implements InputFilterProviderInterface {
public function __construct()
{
parent::__construct('kontakt');
$this->setHydrator(new KontaktHydrator())
->setObject(new Kontakt());
$this->add(array(
'type' => 'Zend\Form\Element\Collection',
'name' => 'firmaKategorien',
'options' => array(
'count' => 0,
'allow_add' => true,
'allow_remove' => true,
'should_create_template' => false,
'target_element' => array(
'type' => 'KontakteManager\Form\KontaktKategorieFieldset'
)
)
));
}
/**
* #return array
\*/
public function getInputFilterSpecification()
{
return array();
}
The CategorieFieldset:
class KontaktKategorieFieldset extends Fieldset {
public function __construct()
{
parent::__construct('kontakteKategorie');
$this->setHydrator(new KontaktKategorieFieldsetHydrator())
->setObject(new KontaktKategorie());
$this->add(array(
'name' => 'id',
'type' => 'Zend\Form\Element\Hidden',
'attributes' => array(
'class' => 'form-control',
),
));
$this->add(array(
'name' => 'bezeichnung',
'type' => 'Zend\Form\Element\Text',
'attributes' => array(
'class' => 'form-control',
),
'options' => array(
'label' => 'Kategorie',
),
));
$this->add(array(
'type' => 'Zend\Form\Element\Collection',
'name' => 'tags',
'options' => array(
'count' => 0,
'allow_add' => true,
'allow_remove' => true,
'should_create_template' => false,
'target_element' => array(
'type' => 'KontakteManager\Form\TagFieldset'
)
)
));
}
And the TagFielset:
class TagFieldset extends Fieldset implements InputFilterProviderInterface {
public function __construct()
{
parent::__construct('Tag');
$this->setHydrator(new TagHydrator())
->setObject(new Tag());
$this->add(array(
'name' => 'id',
'type' => 'Zend\Form\Element\Hidden',
'attributes' => array(
'class' => 'form-control',
),
));
$this->add(array(
'name' => 'mehrsprachig',
'type' => 'Zend\Form\Element\Hidden',
'attributes' => array(
'class' => 'form-control',
),
'options' => array(
'label' => 'Mehrsprachig',
),
));
$this->add(array(
'name' => 'kategorieID',
'type' => 'Zend\Form\Element\Hidden',
'attributes' => array(
'class' => 'form-control',
),
));
$this->add(array(
'name' => 'bezeichnung',
'type' => 'Zend\Form\Element\Text',
'attributes' => array(
'class' => 'form-control',
'readonly' => 'readonly',
),
'options' => array(
'label' => 'Bezeichnung',
),
));
}
/**
* #return array
\*/
public function getInputFilterSpecification()
{
return array();
}
And the View code how i try to display the collections
<h5 class="text-primary"><strong>Kategorien</strong></h5>
<hr>
<?php foreach($kontaktForm->get('firmaKategorien') as $element): ?>
<div class="row">
<div class="col-lg-12">
<div class="col-lg-6">
<?php echo $this->formElement($element->get('bezeichnung')); ?>
</div>
<div class="col-lg-6">
<?php foreach($element->get('tags') as $tag): ?>
<?php echo $this->formElement($tag->get('bezeichnung')); ?>
<?php endforeach; ?>
</div>
</div>
</div>
<?php endforeach; ?>
and here an example result:
<h5 class="text-primary"><strong>Kategorien</strong></h5>
<hr>
<div class="row">
<div class="col-lg-12">
<div class="col-lg-6">
<input type="text" name="firmaKategorien[0][bezeichnung]" class="form-control" value="Druckerei">
</div>
<div class="col-lg-6">
<input type="text" name="firmaKategorien[0][tags][0][bezeichnung]" class="form-control" readonly="readonly" value="">
<input type="text" name="firmaKategorien[0][tags][1][bezeichnung]" class="form-control" readonly="readonly" value="">
</div>
</div>
See if this will make any changes
$kontaktForm->bind($kontakt);
//Add this line
$kontaktForm->setData((Array)$kontakt);
Please post back the error you get
I have a little problem generate captcha in ZF2
Here is my Controller:
public function indexAction()
{
$form = new RegisterForm();
return array('form' => $form);
}
RegisterForm class:
public function __construct($name = null)
{
$this->url = $name;
parent::__construct('register');
$this->setAttributes(array(
'method' => 'post'
));
$this->add(array(
'name' => 'password',
'attributes' => array(
'type' => 'password',
'id' => 'password'
)
));
$this->get('password')->setLabel('Password: ');
$captcha = new Captcha\Image();
$captcha->setFont('./data/captcha/font/arial.ttf');
$captcha->setImgDir('./data/captcha');
$captcha->setImgUrl('./data/captcha');
$this->add(array(
'type' => 'Zend\Form\Element\Captcha',
'name' => 'captcha',
'options' => array(
'label' => 'Captcha',
'captcha' => $captcha,
),
));
$this->add(array(
'name' => 'submit',
'attributes' => array(
'type' => 'button',
'value' => 'Register',
),
));
}
View: index.phtml:
...
<div class="group">
<?php echo $this->formlabel($form->get('captcha')); ?>
<div class="control-group">
<?php echo $this->formElementErrors($form->get('captcha')) ?>
<?php echo $this->formCaptcha($form->get('captcha')); ?>
</div>
</div>
...
Above code generate png images in data/captcha folder, but i can't generate them in view.
FireBug shows img element and url, but url to image seems to be empty.
Thanks for any help.
You have to set the img url correctly and define the route in your module.config.php
Controller
public function indexAction()
{
$form = new RegisterForm($this->getRequest()->getBaseUrl().'test/captcha');
return array('form' => $form);
}
remember to change the test/captcha to your own base url
in your registerForm class
public function __construct($name)
{
//everything remain the same, just change the below statement
$captcha->setImgUrl($name);
}
add this to your module.config.php, as your main route child
'may_terminate' => true,
'child_routes' => array(
'registerCaptcha' => array(
'type' => 'segment',
'options' => array(
'route' => '/[:action[/]]',
'constraints' => array(
'action' => '[a-zA-Z][a-zA-Z0-9_-]*',
),
'defaults' => array(
'action' => 'register',
),
),
),
'captchaImage' => array(
'type' => 'segment',
'options' => array(
'route' => '/captcha/[:id]',
'constraints' => array(
'action' => '[a-zA-Z][a-zA-Z0-9_-]*',
),
'defaults' => array(
'controller' => 'controller',
'action' => 'generate',
),
),
),
),
remember to change the controller under captcha image, the action generate is actually generating the captcha image file
add this to your controller file as well
public function generateAction()
{
$response = $this->getResponse();
$response->getHeaders()->addHeaderLine('Content-Type', "image/png");
$id = $this->params('id', false);
if ($id) {
$image = './data/captcha/' . $id;
if (file_exists($image) !== false) {
$imagegetcontent = #file_get_contents($image);
$response->setStatusCode(200);
$response->setContent($imagegetcontent);
if (file_exists($image) == true) {
unlink($image);
}
}
}
return $response;
}
with these, it should be working fine