ZendFramework 2 - How to edit form data with fieldsets? - php

I'm trying to learn ZF2, and I am not able to edit the data in the edit form. I have two classes Pessoa and Endereco and I have a form to edit the data, but it only changes the data related to Pessoa, those about the Endereco is stored as blank.
And when trying to add a new record (add action) i get the following error:
Fatal error: Cannot use object of type Pessoa\Model\Pessoa as array in /opt/lampp/htdocs/cad/module/Pessoa/src/Pessoa/Model/Pessoa.php on line 23
Pessoa.php
class Pessoa
{
public $id;
public $nome;
public $dtNasc;
public $endereco;
protected $inputFilter;
public function __construct()
{
$this->endereco = new Endereco();
}
public function exchangeArray($data)
{
$this->id = (!empty($data['id'])) ? $data['id'] : null;
$this->nome = (!empty($data['nome'])) ? $data['nome'] : null;
$this->dtNasc = (!empty($data['dtNasc'])) ? $data['dtNasc'] : null;
//$this->getEndercoInstance();
$this->endereco->exchangeArray($data);
/*if (isset($data["endereco"]))
{
if (!is_object($this->endereco)) $this->endereco = new Endereco();
$this->endereco->exchangeArray($data["endereco"]);
}*/
}
public function getArrayCopy()
{
$data = get_object_vars($this);
if (is_object($this->endereco)) {
$data["endereco"] = $this->endereco->getArrayCopy();
}
return $data;
}
public function setEndereco($end)
{
$this->endereco = $end;
}
private function getEndercoInstance()
{
$di = new Zend\Di;
$config = new Zend\Di\Configuration(array(
'instance' => array(
'Pessoa' => array(
// letting Zend\Di find out there's a $bar to inject where possible
'parameters' => array('endereco' => 'Endereco\Model\Endereco'),
)
)
));
$config->configure($di);
$pessoa = $di->get('Pessoa');
$this->endereco = $pessoa->endereco;
}
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' => 'nome',
'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;
}
}
Endereco.php
class Endereco
{
public $rua;
public $bairro;
public function exchangeArray($data)
{
$this->rua = (!empty($data["rua"])) ? $data["rua"] : null;
$this->bairro = (!empty($data["bairro"])) ? $data["bairro"] : null;
}
public function getArrayCopy()
{
return get_object_vars($this);
}
}
PessoaController.php add e edit actions
public function addAction()
{
$form = new PessoaForm();
$form->get('submit')->setValue('Add');
$request = $this->getRequest();
if ($request->isPost()) {
$pessoa = new Pessoa();
//$form->setInputFilter($pessoa->getInputFilter());
$form->setData($request->getPost());
if ($form->isValid()) {
$pessoa->exchangeArray($form->getData());
$this->getPessoaTable()->savePessoa($pessoa);
// Redirect to list of pessoa
return $this->redirect()->toRoute('pessoa');
}
}
return array('form' => $form);
}
public function editAction()
{
$id = (int) $this->params()->fromRoute('id', 0);
if (!$id) {
return $this->redirect()->toRoute('pessoa', array(
'action' => 'add'
));
}
try {
$pessoa = $this->getPessoaTable()->getPessoa($id);
}
catch (\Exception $ex) {
return $this->redirect()->toRoute('pessoa', array(
'action' => 'index'
));
}
$form = new PessoaForm();
$form->bind($pessoa);
$form->get('submit')->setAttribute('value', 'Edit');
$request = $this->getRequest();
if ($request->isPost()) {
//$form->setInputFilter($pessoa->getInputFilter());
$form->setData($request->getPost());
if ($form->isValid()) {
$this->getPessoaTable()->savePessoa($pessoa);
// Redirect to list of pessoa
return $this->redirect()->toRoute('pessoa');
}else{
echo "not valid";
}
}
return array(
'id' => $id,
'form' => $form,
);
}
EnderecoFieldSet.php
class EnderecoFieldSet extends Fieldset
{
public function __construct($name = null)
{
parent::__construct('endereco');
$this->setHydrator(new ArraySerializableHydrator())
->setObject(new Endereco());
$this->add(array(
'name' => 'rua',
'option' => array(
'label' => 'Rua: ',
),
));
$this->add(array(
'name' => 'bairro',
'option' => array(
'label' => 'Bairro: ',
),
));
}
}
PessoaFieldSet.php
class PessoaFieldSet extends Fieldset
{
//public $endereco;
public function __construct()
{
//$this->endereco = new Endereco()
$this->init();
}
public function init()
{
parent::__construct('pessoa');
$this->setHydrator(new ArraySerializableHydrator())
->setObject(new Pessoa());
$this->add(array(
'name' => 'id',
'type' => 'Hidden',
));
$this->add(array(
'name' => 'nome',
'type' => 'Text',
'options' => array(
'label' => 'Nome:',
),
'attributes' => array(
'required' => 'required',
),
));
$this->add(array(
'name' => 'dtNasc',
'type' => 'Text',
'options' => array(
'label' => 'Data Nascimento:',
),
));
$this->add(array(
'type' => 'Pessoa\Form\EnderecoFieldSet',
'name' => 'endereco',
'options' => array(
'label' => 'endereco',
),
));
}
PessoaForm.php
class PessoaForm extends Form
{
public function __construct()
{
$this->init();
}
public function init()
{
// we want to ignore the name passed
parent::__construct('pessoa_form');
$this->setHydrator(new ArraySerializableHydrator());
//->setInputFilter(new InputFilter());
$this->add(array(
'type' => 'Pessoa\Form\PessoaFieldSet',
'options' => array(
'use_as_base_fieldset' => true
)
));
$this->add(array(
'type' => 'Zend\Form\Element\Csrf',
'name' => 'csrf'
));
$this->add(array(
'name' => 'submit',
'type' => 'Submit',
'attributes' => array(
'value' => 'Go',
'id' => 'submitbutton',
),
));
}
}
And trying to add a new record (add action) i get the following error:
Fatal error: Cannot use object of type Pessoa\Model\Pessoa as array in /opt/lampp/htdocs/cad/module/Pessoa/src/Pessoa/Model/Pessoa.php on line 23
Please, can anyone help me?

So let me explain better my self,
You are sending an array to the method
exchangeArray($data);
but $data is not an array;
Example of Array:
$data['username'] = 'someuser';
$data['email'] = 'someuser#someuser.com';
$data['phone'] = '235346346';
print_r($data);die;
//output:
//Array ( [username] => someuser [email] => someuser#someuser.com [phone] => 235346346 )
Example Object:
$data['username'] = 'someuser';
$data['email'] = 'someuser#someuser.com';
$data['phone'] = '235346346';
$object = (object)$data;
print_r($object);die;
//Output
//stdClass Object ( [username] => someuser [email] => someuser#someuser.com [phone] => 235346346 )
So i reproduce part of the code you have above and i gave to the method exchangeArray($data); of type Array and i got no errors then i gave to the method exchangeArray($object); and the result was
Fatal error: Cannot use object of type stdClass as array in /blah/blah/... on line 39
So Basically in your method you are passing $data of type object and not Array

Related

Fatal error: Call to a member function setAttribute() on null when creating form using zend framework 2

Fatal error: Call to a member function setAttribute() on null in \module\Admin\view\admin\index\login.phtml when trying to create form using Zend Framework
Can somebody help me with where am doing wrong. I pasted all the code.
\module\Admin\src\Admin\Controller\LoginController.php
class LoginController extends AbstractActionController
{
protected $usersTable = null;
public function indexAction()
{
return new ViewModel();
}
public function loginAction(){
$form = new LoginForm();
$form->get('submit')->setValue('Login');
$request = $this->getRequest();
if($request->isPost()){
$login = new Login();
$form->setInputFilter($login->getInputFilter());
$form->setData($request->getPost());
if($form->isValid()){
$login->exchangeArray($form->getData());
$this->getLoginDetails()->saveLoginForm($login);
// Redirect to list of albums
return $this->redirect()->toRoute('index');
}
}
return array('form' => $form);
}
}
\module\Admin\src\Admin\Form
namespace Admin\Form;
use Zend\Form\Form;
class LoginForm extends Form
{
public function _construct()
{
parent::_construct('admin');
$this->add(array(
'name' => 'username',
'type' => 'Text',
'options' => array(
'label' => 'Username',
'id' => 'txtUsername',
),
));
$this->add(array(
'name' => 'password',
'type' => 'password',
'options' => array(
'label' => 'Password',
'id' => 'txtPassword',
),
));
$this->add(array(
'name' => 'submit',
'type' => 'Submit',
'attributes' => array(
'value' => 'Login',
'id' => 'btnSubmit',
),
));
}
}
\module\Admin\src\Admin\Model
namespace Admin\Model;
use Zend\InputFilter\InputFilter;
use Zend\InputFilter\InputFilterAwareInterface;
use Zend\InputFilter\InputFilterInterface;
class Login implements InputFilterAwareInterface{
public $username;
public $password;
protected $inputFilter;
public function exchangeArray($data)
{
$this->artist = (isset($data['username'])) ? $data['username'] : null;
$this->title = (isset($data['password'])) ? $data['password'] : null;
}
public function setInputFilter(InputFilterInterface $inputFilter){
throw new \Exception("not used");
}
public function getInputFilter(){
if(!$this->inputFilter){
$inputFilter = new InputFilter();
$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' => 50,
),
),
),
));
$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' => 50,
),
),
),
));
$this->inputFilter = $inputFilter;
}
return $this->inputFilter;
}
\module\Admin\view\admin\index
<?php
$form = $this->form;
$form->setAttribute('action', $this->url('admin', array('action' => 'login')));
$form->prepare();
echo $this->form()->openTag($form);
echo $this->formRow($form->get('username'));
echo $this->formRow($form->get('password'));
echo $this->formSubmit($form->get('submit'));
echo $this->form()->closeTag();
echo $this->$form;
What is $form = $this->form?
Is used in controller? Where do you pass anything on $this->form. Its null, like you see error. You can var_dump($form) to check it. You need to create your form first with:
$form = new \My\Form();
If $form is null inside login.phtml, thats mean you dont passed $form variable to phtml script (we dont see it in your code)
When you want to change element attribute you have to get that element by using getElement function then use zend form function. Try below code it will work for you.
$form = new LoginForm();
$form->getElement('submit')->setValue('get');

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']),
),
),
),
)); ...

Why is my SQL query running twice?

I am using the Zend Framework 2 and notice my sql queries are running twice when pulling values from the database to use in my Forms. I can see in the developertool that it is running twice (two different run times). It only happens with the form elements (not when I echo query results into a table)
I used the below link as a guide:
http://samminds.com/2013/03/zendformelementselect-and-database-values/
Thanks
M
Controller Action
public function indexAction() //Display the pro greetings page
{
$this->layout()->setVariable('menu', 'verified');
$dbAdapter = $this->getServiceLocator()->get('Zend\Db\Adapter\Adapter');
$form = new ProLicenceForm($dbAdapter);
$form->get('submit')->setValue('Submit');
$pro_id='22';
$proBackEnd = new ProSide($dbAdapter);
$form->get('pro_id')->setValue($pro_id);
// $user_id=$this->zfcUserAuthentication()->getIdentity()->getId(); //causes error if not register need to block or add logic to redirect
// $form->get('user_id')->setValue($user_id); //pass the user id from the user module
$request = $this->getRequest();
if ($request->isPost()) {
$proLicence = new ProLicence();
$form->setInputFilter($proLicence->getInputFilter());
$form->setData($request->getPost());
if ($form->isValid()) {
$proLicence->exchangeArray($form->getData());
$this->getProLicenceTable()->saveProLicence($proLicence);
// return $this->redirect()->toRoute('pro', array('action'=>'proVerification')); //redirect to next step
}
else {
echo "ERROR HOMMIE";
}
}
return array(
'form' => $form,
'proLicences' => $proBackEnd->getProSideLicence($pro_id),
);
}
Form
<?php
namespace Pro\Form;
use Zend\Form\Form;
use Zend\Db\Adapter\AdapterInterface;
class ProLicenceForm extends Form
{
public function __construct(AdapterInterface $dbAdapter)
{
// $this->setDbAdapter($dbAdapter);
$this->adapter =$dbAdapter;
// we want to ignore the name passed
parent::__construct('pro-licence-form');
$this->add(array(
'name' => 'pro_id',
'type' => 'Hidden',
));
$this->add(array(
'name' => 'licence_id',
'type' => 'Hidden',
'options' => array(
),
'attributes' => array(
//'required' => 'required'
)
));
$this->add(array(
'name' => 'licence_name_id',
'type' => 'Zend\Form\Element\Select',
'options' => array(
'label' => 'Licence',
'value_options' => $this->getLicenceOptions(),
'empty_option' => '--- please choose ---'
),
'attributes' => array(
'placeholder' => 'Choose all that apply'
)
));
$this->add(array(
'name' => 'licence_number',
'type' => 'Text',
'options' => array(
'label' => 'Licence Number'
)
));
$this->add(array(
'name' => 'submit',
'type' => 'Submit',
'options' => array(
'label'=> 'Primary Button',
),
'attributes' => array(
'value' => 'Go',
'id' => 'submitbutton',
),
));
}
/*
* SQL statements used to bring in optiosn
*/
public function getLicenceOptions()
{
$dbAdapter = $this->adapter;
$sql = 'SELECT licence_name_id,licence_name FROM licence_name_table ORDER BY licence_name';
$statement = $dbAdapter->query($sql);
$result = $statement->execute();
$selectData = array();
foreach ($result as $res) {
$selectData[$res['licence_name_id']] = $res['licence_name'];
}
return $selectData;
}
}

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

Adapter Db\NoRecordExists Error [Zend 2]

Catchable fatal error: Argument 1 passed to
Zend\Validator\Db\AbstractDb::setAdapter() must be an instance of
Zend\Db\Adapter\Adapter, null given, called in
/home2/mapasgua/vendor/zendframework/zendframework/library/Zend/Validator/AbstractValidator.php
on line 142 and defined in
/home2/mapasgua/vendor/zendframework/zendframework/library/Zend/Validator/Db/AbstractDb.php
on line 168
Module.php
<?php
namespace User;
use Zend\Mvc\MvcEvent;
use Zend\Mvc\ModuleRouteListener;
use User\Model\UsersTable;
use User\Model\Users;
class Module
{
public function onBootstrap(MvcEvent $e)
{
ini_set('date.timezone', 'America/Sao_Paulo');
$e->getApplication()->getServiceManager()->get('translator');
$eventManager = $e->getApplication()->getEventManager();
$moduleRouteListener = new ModuleRouteListener();
$moduleRouteListener->attach($eventManager);
$e->getApplication()->getEventManager()->getSharedManager()->attach('Zend\Mvc\Controller\AbstractActionController', 'dispatch', function($e) {
$controller = $e->getTarget();
$controllerClass = get_class($controller);
$moduleNamespace = substr($controllerClass, 0, strpos($controllerClass, '\\'));
$config = $e->getApplication()->getServiceManager()->get('config');
if (isset($config['module_layouts'][$moduleNamespace])) {
$controller->layout($config['module_layouts'][$moduleNamespace]);
}
}, 100);
}
public function getAutoloaderConfig()
{
return array(
// 'Zend\Loader\ClassMapAutoloader' => array(
// __DIR__ . '/autoload_classmap.php',
// ),
'Zend\Loader\StandardAutoloader' => array(
'namespaces' => array(
__NAMESPACE__ => __DIR__ . '/src/' . __NAMESPACE__,
),
),
);
}
public function getServiceConfig()
{
return array(
'factories' => array(
'User\Model\UsersTable' => function($sm) {
$dbAdapter = $sm->get('Zend\Db\Adapter\Adapter');
$table = new UsersTable($dbAdapter);
return $table;
},
'User\Model\Users' => function($sm) {
$dbAdapter = $sm->get('Zend\Db\Adapter\Adapter');
$users = new Users();
$users->setDbAdapter($dbAdapter);
return $users;
},
),
);
}
public function getConfig()
{
return include __DIR__ . '/config/module.config.php';
}
}
Users.php
<?php
namespace User\Model;
use Zend\InputFilter\InputFilter;
use Zend\InputFilter\Factory as InputFactory;
use Zend\InputFilter\InputFilterInterface;
use Zend\InputFilter\InputFilterAwareInterface;
use Zend\Db\Adapter\Adapter;
use Zend\Validator\Db\AbstractDb;
class Users implements InputFilterAwareInterface
{
public $id;
public $name;
public $username;
public $password;
protected $inputFilter;
public $_dbAdapter;
public function exchangeArray($data)
{
$this->id = (isset($data['id'])) ? $data['id'] : null;
$this->name = (isset($data['name'])) ? $data['name'] : null;
$this->username = (isset($data['username'])) ? $data['username'] : null;
$this->password = (isset($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 setDbAdapter($dbAdapter)
{
$this->_dbAdapter = $dbAdapter;
}
public function getDbAdapter()
{
return $this->_dbAdapter;
}
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' => 'name',
'required' => true,
'filters' => array(
array('name' => 'StripTags'),
array('name' => 'StringTrim'),
),
'validators' => array(
array(
'name' => 'StringLength',
'options' => array(
'encoding' => 'UTF-8',
'min' => 3,
'max' => 32,
),
),
),
)));
$inputFilter->add($factory->createInput(array(
'name' => 'username',
'required' => true,
'filters' => array(
array('name' => 'StripTags'),
array('name' => 'StringTrim'),
),
'validators' => array(
array(
'name' => 'EmailAddress',
'options' => array(
'encoding' => 'UTF-8',
'min' => 3,
'max' => 32,
'message' => 'Endereço de e-mail invalido',
),
),
array(
'name' => 'Db\NoRecordExists',
'options' => array(
'table' => 'users',
'field' => 'username',
'adapter' => $this->getDbAdapter(),
'exclude' => array(
'field' => 'id',
'value' => !is_null( $this->id ) && !empty( $this->id ) ? $this->id : 0,
),
),
),
),
)));
$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' => 3,
'max' => 32,
),
),
),
)));
$inputFilter->add($factory->createInput(array(
'name' => 'retype-password',
'required' => true,
'filters' => array(
array('name' => 'StripTags'),
array('name' => 'StringTrim'),
),
'validators' => array(
array(
'name' => 'StringLength',
'options' => array(
'encoding' => 'UTF-8',
'min' => 3,
'max' => 32,
),
),
array(
'name' => 'Identical',
'options' => array(
'token' => 'password', //I have tried $_POST['password'], but it doesnt work either
),
),
),
)));
$this->inputFilter = $inputFilter;
}
return $this->inputFilter;
}
}
UserController.php
namespace User\Controller;
<?php
use Zend\Mvc\Controller\AbstractActionController;
use Zend\Authentication\AuthenticationService;
use Zend\Authentication\Adapter\DbTable as AuthAdapter;
use Zend\Authentication\Result as Result;
use Zend\Mail;
use User\Form\LoginForm;
use User\Form\RegisterForm;
use User\Form\RecuperarForm;
use User\Model\Users;
class UserController extends AbstractActionController
{
protected $usersTable;
public function configAction()
{
$auth = new AuthenticationService();
$form = new RegisterForm();
$identity = null;
if ($auth->hasIdentity()) {
$dados = $this->getUsersTable()->getUser($auth->getIdentity());
$request = $this->getRequest();
if ($request->isPost()) {
$users = new Users();
$post = $request->getPost();
$form->setInputFilter($users->getInputFilter());
$form->setData($post);
if ($form->isValid()) {
$users->exchangeArray($post);
$this->getUsersTable()->saveUsers($users);
$this->flashMessenger()->addMessage("Configurações atualizadas com sucesso.");
return $this->redirect()->toRoute('painel');
}
} else {
$post = array(
'id' => $dados->id,
'name' => $dados->name,
'username' => $dados->username,
);
$form->setData($post);
}
} else {
return $this->redirect()->toRoute('login');
}
return array(
'form' => $form,
);
}
Your problem is you have defined a factory for Users but you don't use it. The line $users = new Users(); directly instantiates the object without using your factory.
Change it to
$users = $this->getServiceLocator()->get('User\Model\Users');
As your object relies on Zend\Db\Adapter\Adapter you need your factory to inject this for you.

Categories