Argument 1 passed to Application\Controller\IndexController::__construct() must be an instance of Application\Model\EmployeeTable, none given - zend-framework2

I stuck With this Issue in Zd2 and knocking my head from last 2 days but not come up with any solution. Will be very Appreciable If anyone Can help me out with the below given error.
Argument 1 passed to Application\Controller\IndexController::__construct() must be an instance of Application\Model\EmployeeTable, none given
Here is my Application Module Config file module.config.php
namespace Application;
use Zend\Router\Http\Literal; use Zend\Router\Http\Segment; use
Zend\ServiceManager\Factory\InvokableFactory;
return [
[
'controllers' => [
'invokables' => [
'Application\Controller\Index' => 'Application\Controller\IndexController',
],
'factories' => [
'Application\Controller\Index' => 'Application\Factory\IndexControllerFactory'
],
]
],
'router' => [
'routes' => [
'home' => [
'type' => Literal::class,
'options' => [
'route' => '/',
'defaults' => [
'controller' => Controller\IndexController::class,
'action' => 'index',
],
],
],
'application' => [
'type' => Segment::class,
'options' => [
'route' => '/application[/:action]',
'defaults' => [
'controller' => Controller\IndexController::class,
'action' => 'index',
],
],
],
],
],
'view_manager' => [
'display_not_found_reason' => true,
'display_exceptions' => true,
'doctype' => 'HTML5',
'not_found_template' => 'error/404',
'exception_template' => 'error/index',
'template_map' => [
'layout/layout' => __DIR__ . '/../view/layout/layout.phtml',
'application/index/index' => __DIR__ . '/../view/application/index/index.phtml',
'error/404' => __DIR__ . '/../view/error/404.phtml',
'error/index' => __DIR__ . '/../view/error/index.phtml',
],
'template_path_stack' => [
__DIR__ . '/../view',
],
], ];
Application Index Controller
table = $table;
}
public function indexAction() {
$view = new ViewModel([
'data' => $this->table->fetchAll(),
]);
return $view;
} }
Module.php file
class Module implements ConfigProviderInterface {
const VERSION = '3.0.3-dev';
public function getConfig()
{
return include __DIR__ . '/../config/module.config.php';
}
public function getServiceConfig() {
return [
'factories' => [
Model\EmployeeTable::class => function ($container) {
$tableGateway = $container>get(Model\EmployeeTableGateway::class);
$table = new Model\EmployeeTable($tableGateway);
return $table;
},
Model\EmployeeTableGateway::class => function ($container) {
$dbAdapter = $container->get(AdapterInterface::class);
$resultSetPrototype = new ResultSet();
$resultSetPrototype->setArrayObjectPrototype(new Employee());
return new TableGateway('employee', $dbAdapter, null, $resultSetPrototype);
},
],
];
}
public function getControllerConfig() {
return [
'factories' => [
Controller\IndexController::class => function($container) {
return new Controller\IndexController(
$container->get(EmployeeTable::class)
);
},
],
];
} }
Model Employee
class Employee {
public $id;
public $emp_name;
public $emp_job;
public function exchangeArray($data) {
$this->id = (!empty($data['id'])) ? $data['id'] : null;
$this->emp_name = (!empty($data['emp_name'])) ? $data['emp_name'] : null;
$this->emp_job = (!empty($data['emp_job'])) ? $data['emp_job'] : null;
} }
Model EmployeeTable
use Zend\Db\TableGateway\TableGateway;
use Zend\Db\TableGateway\TableGatewayInterface;
class EmployeeTable {
protected $tableGateway;
public function __construct(TableGatewayInterface $tableGateway) { $this->tableGateway = $tableGateway; }
public function fetchAll() {
$resultSet = $this->tableGateway->select();
return $resultSet;
} }
Please help !

I the above Module.php, either write on top of the class
use Model\EmployeeTable;
Or, set an aliases to "Model\EmployeeTable::class"
public function getServiceConfig() {
return [
'factories' => [
Model\EmployeeTable::class => function ($container) {
$tableGateway = $container>get(Model\EmployeeTableGateway::class);
$table = new Model\EmployeeTable($tableGateway);
return $table;
},
Model\EmployeeTableGateway::class => function ($container) {
$dbAdapter = $container->get(AdapterInterface::class);
$resultSetPrototype = new ResultSet();
$resultSetPrototype->setArrayObjectPrototype(new Employee());
return new TableGateway('employee', $dbAdapter, null, $resultSetPrototype);
},
],
'aliases' => array(
EmployeeTable::class => Model\EmployeeTable::class
)
];
}

Related

Show username of logged in user in zf2

I have login and logout system in ZF2. I want to show username of logged in user when he/she is logged in. Screen shot is given below:
I have different views like view/provinces/index.phtml, view/districts/index.phtml, etc.
I have layout.phtml in view/layout/layout.phtml, in which I described layout for admin which is for every view. So It is necessary to access username of logged in user in layout.phtml.
I have also corresponding controllers like Controller/ProvincesController.php, Controller/DistrictsController.php etc. I can access username of logged in user in Controller/ProvincesController.php etc by the code:
public function getAuthService()
{
$this->authservice = $this->getServiceLocator()->get('AuthService');
return $this->authservice;
}
$username = $this->getAuthService()->getStorage()->read();
But I am unable to access value of username of logged in user in layout.phtml.
So if anyone know about it or have simple idea or practice about it, then let me know please.
Module.php:
<?php
namespace Admin;
use Admin\Model\Profile;
use Admin\Model\ProfileTable;
use Admin\Model\Provinces;
use Admin\Model\ProvincesTable;
use Admin\Model\Districts;
use Admin\Model\DistrictsTable;
use Admin\Model\User;
use Admin\Model\UserTable;
use Zend\Db\ResultSet\ResultSet;
use Zend\Db\TableGateway\TableGateway;
use Zend\Mvc\ModuleRouteListener;
use Zend\Mvc\MvcEvent;
use Zend\ModuleManager\Feature\AutoloaderProviderInterface;
use Zend\Authentication\Adapter\DbTable as DbTableAuthAdapter;
use Zend\Authentication\AuthenticationService;
class Module implements AutoloaderProviderInterface
//class Module
{
public function getConfig()
{
return include __DIR__ . '/config/module.config.php';
}
public function getServiceConfig()
{
return array(
'abstract_factories' => array(),
'aliases' => array(),
'factories' => array(
// SERVICES
'AuthService' => function($sm) {
$dbAdapter = $sm->get('Zend\Db\Adapter\Adapter');
$dbTableAuthAdapter = new DbTableAuthAdapter($dbAdapter, 'user','username','password', 'MD5(?)');
$authService = new AuthenticationService();
$authService->setAdapter($dbTableAuthAdapter);
return $authService;
},
// DB
'UserTable' => function($sm) {
$tableGateway = $sm->get('UserTableGateway');
$table = new UserTable($tableGateway);
return $table;
},
'UserTableGateway' => function ($sm) {
$dbAdapter = $sm->get('Zend\Db\Adapter\Adapter');
$resultSetPrototype = new ResultSet();
$resultSetPrototype->setArrayObjectPrototype(new User());
return new TableGateway('user', $dbAdapter, null,
$resultSetPrototype);
},
// FORMS
'LoginForm' => function ($sm) {
$form = new \Admin\Form\LoginForm();
$form->setInputFilter($sm->get('LoginFilter'));
return $form;
},
// FILTERS
'LoginFilter' => function ($sm) {
return new \Admin\Form\LoginFilter();
},
'Admin\Model\ProvincesTable' => function($sm) {
$tableGateway = $sm->get('ProvincesTableGateway');
$table = new ProvincesTable($tableGateway);
return $table;
},
'ProvincesTableGateway' => function ($sm) {
$dbAdapter = $sm->get('Zend\Db\Adapter\Adapter');
$resultSetPrototype = new ResultSet();
$resultSetPrototype->setArrayObjectPrototype(new Provinces());
return new TableGateway('provinces', $dbAdapter, null, $resultSetPrototype);
},
'Admin\Model\DistrictsTable' => function($sm) {
$tableGateway = $sm->get('DistrictsTableGateway');
$table = new DistrictsTable($tableGateway);
return $table;
},
'DistrictsTableGateway' => function ($sm) {
$dbAdapter = $sm->get('Zend\Db\Adapter\Adapter');
$resultSetPrototype = new ResultSet();
$resultSetPrototype->setArrayObjectPrototype(new Districts());
return new TableGateway('districts', $dbAdapter, null, $resultSetPrototype);
},
),
'invokables' => array(),
'services' => array(),
'shared' => array(),
);
}
public function getAutoloaderConfig()
{
return array(
'Zend\Loader\StandardAutoloader' => array(
'namespaces' => array(
// if we're in a namespace deeper than one level we need to fix the \ in the path
__NAMESPACE__ => __DIR__ . '/src/' . str_replace('\\', '/' , __NAMESPACE__),
),
),
);
}
}
Thanks in advance.
The recommend way would be to use identity (https://framework.zend.com/manual/2.4/en/modules/zend.view.helpers.identity.html) view helper. Then in any view model you could use it as follow:
if ($user = $this->identity()) {
echo 'Logged in as ' . $this->escapeHtml($user->getUsername());
} else {
echo 'Not logged in';
}
In order to make it work you have to register your authentication service under specific name- Zend\Authentication\AuthenticationService.
So in your module.config.php file, add to service_manager:
'service_manager' => array(
'aliases' => array(
'Zend\Authentication\AuthenticationService' => 'AuthService', // <--- this line
),
'invokables' => array(
'AuthService' => 'Your\Authentication\Class',
),
),
Then you should be able to use identity controller plugin and view helper.
In your case, Module.php should look like this:
...
public function getServiceConfig()
{
return array(
'abstract_factories' => array(),
'aliases' => array(
'Zend\Authentication\AuthenticationService' => 'AuthService', // <--- this line
),
'factories' => array(
// SERVICES
'AuthService' => function($sm) {
$dbAdapter = $sm->get('Zend\Db\Adapter\Adapter');
$dbTableAuthAdapter = new DbTableAuthAdapter($dbAdapter, 'user','username','password', 'MD5(?)');
$authService = new AuthenticationService();
$authService->setAdapter($dbTableAuthAdapter);
return $authService;
},
// DB
'UserTable' => function($sm) {
$tableGateway = $sm->get('UserTableGateway');
$table = new UserTable($tableGateway);
return $table;
},
'UserTableGateway' => function ($sm) {
$dbAdapter = $sm->get('Zend\Db\Adapter\Adapter');
$resultSetPrototype = new ResultSet();
$resultSetPrototype->setArrayObjectPrototype(new User());
return new TableGateway('user', $dbAdapter, null,
$resultSetPrototype);
},
// FORMS
'LoginForm' => function ($sm) {
$form = new \Admin\Form\LoginForm();
$form->setInputFilter($sm->get('LoginFilter'));
return $form;
},
// FILTERS
'LoginFilter' => function ($sm) {
return new \Admin\Form\LoginFilter();
},
'Admin\Model\ProvincesTable' => function($sm) {
$tableGateway = $sm->get('ProvincesTableGateway');
$table = new ProvincesTable($tableGateway);
return $table;
},
'ProvincesTableGateway' => function ($sm) {
$dbAdapter = $sm->get('Zend\Db\Adapter\Adapter');
$resultSetPrototype = new ResultSet();
$resultSetPrototype->setArrayObjectPrototype(new Provinces());
return new TableGateway('provinces', $dbAdapter, null, $resultSetPrototype);
},
'Admin\Model\DistrictsTable' => function($sm) {
$tableGateway = $sm->get('DistrictsTableGateway');
$table = new DistrictsTable($tableGateway);
return $table;
},
'DistrictsTableGateway' => function ($sm) {
$dbAdapter = $sm->get('Zend\Db\Adapter\Adapter');
$resultSetPrototype = new ResultSet();
$resultSetPrototype->setArrayObjectPrototype(new Districts());
return new TableGateway('districts', $dbAdapter, null, $resultSetPrototype);
},
),
'invokables' => array(),
'services' => array(),
'shared' => array(),
);
}
...
Then in your layout or any other .phtml file:
layout.phtml
...
<?php if ($this->identity()): ?>
<p>Welcome, <?php echo $this->identity()->getUsername(); ?></p>
<?php endif; ?>
Taking help of Mr. SzymonM's answer, I changed my Module.php as suggested by him, and write the following simple code in layout.phtml
This solve my issue and username is shown with first letter in Upper case.
<?php
if ($this->identity())
{
echo ucfirst($this->identity());
}
?>
//ucfirst is php function which make first letter Uppercase.

How to validate if 'email' exists Zend Framework 2

I want to use NoRocordExists to validate if email exists before insert the information inside the mysql DB but i don't get how can i call $dbapater.
This is my code of my inputfilter class
$norecord_exists = new NoRecordExists(
array(
'table' => 'users',
'field' => 'email',
'adapter' => $dbadapter
)
);
$norecord_exists->setMessage('Email already exists !', 'recordFound');
$this->add(array(
'name' => 'email',
'required' => true,
'filters' => array(
array('name' => 'StringTrim'),
),
'validators' => array(
$norecord_exists,
array(
'name'=>'EmailAddress',
'options'=> array(
'allowWhiteSpace'=>true,
'messages' => array(
\Zend\Validator\EmailAddress::INVALID_HOSTNAME=>'Email incorrecto',
),
),
),
)
));
With ZF2, I advise you to use FactoryInterface like this :
UserFormFactory.php
<?php
namespace User\Form\Service;
use User\Form\UserForm;
use Zend\ServiceManager\FactoryInterface;
use Zend\ServiceManager\ServiceLocatorInterface;
class UserFormFactory implements FactoryInterface
{
/**
* #param ServiceLocatorInterface $serviceLocator
* #return UserForm
*/
public function createService(ServiceLocatorInterface $serviceLocator)
{
/* #var ServiceLocatorInterface $sl */
$sl = $serviceLocator->getServiceLocator();
$form = new UserForm();
$form->setDbAdapter($sl->get('Zend\Db\Adapter\Adapter'));
return $form;
}
}
UserForm.php
<?php
namespace User\Form;
use Zend\Db\Adapter\AdapterInterface;
use Zend\Form\Form;
use Zend\InputFilter\InputFilterProviderInterface;
class UserForm extends Form implements InputFilterProviderInterface
{
/**
* #var AdapterInterface
*/
protected $dbAdapter;
/**
* Initialisation
*/
public function init()
{
$this->add([
'name' => 'email',
'type' => 'Email',
'options' => [
'label' => 'Email',
],
'attributes' => [
'class' => 'form-control',
'required' => 'required',
],
]);
// ...
$this->add([
'name' => 'submit',
'type' => 'Submit',
'attributes' => [
'value' => 'Connexion',
'class' => 'btn btn-default',
],
]);
}
/**
* InputFilter
*
* #return array
*/
public function getInputFilterSpecification()
{
return [
'email' => [
'required' => true,
'filters' => [
['name' => 'StripTags'],
['name' => 'StringTrim'],
['name' => 'StringToLower'],
],
'validators' => [
[
'name' => 'EmailAddress',
], [
'name' => 'Db\NoRecordExists',
'options' => [
'table' => 'user',
'field' => 'email',
'adapter' => $this->getDbAdapter(),
],
],
],
],
// ...
];
}
/**
* #return AdapterInterface
*/
public function getDbAdapter()
{
return $this->dbAdapter;
}
/**
* #param AdapterInterface $dbAdapter
* #return UserForm
*/
public function setDbAdapter(AdapterInterface $dbAdapter)
{
$this->dbAdapter = $dbAdapter;
return $this;
}
}
module.config.php
return [
'form_elements' => [
'factories' => [
'UserForm' => 'User\Form\Service\UserFormFactory',
],
],
];
Finally, in your controller
$form = $this->getServiceLocator('FormElementManager')->get('UserForm');
//..
if ($form->isValid()) // ...
You need to move this code
$norecord_exists = new NoRecordExists(
array(
'table' => 'users',
'field' => 'email',
'adapter' => $dbadapter
)
);
$norecord_exists->isValid(EMAIL_FROM_THE_FORM_FIELD) {
return false; //email exists
}
return true; // email doen't exists
in your Controller or in a separate service/factory. $dbadapter usually holds the instance to your Zend\Db\Adaptr\Adapter or any other configuration you have.

How to validate empty input in Zend Framework 2

I'm doing a registration form in ZF2, but I don't get how to validate. Validation seems not working.
I'm adding the validators array, but it doesn't work anyways. I don't know how can I fix that.
This is my code of controller:
namespace Application\Controller;
use Zend\Mvc\Controller\AbstractActionController;
use Zend\View\Model\ViewModel;
use Application\Form\Formularios;
use Zend\Db\Adapter\Adapter;
use Application\Modelo\Entity\Usuarios;
class FormularioController extends AbstractActionController
{
public $dbAdapter;
public function indexAction()
{
return new ViewModel();
}
public function registroAction()
{
if($this->getRequest()->isPost())
{
$this->dbAdapter=$this->getServiceLocator()->get('Zend\Db\Adapter');
$u=new Usuarios($this->dbAdapter);
//echo "se recibiĆ³ el post";exit;
$data = $this->request->getPost();
$u->addUsuario($data);
return $this->redirect()->toUrl($this->getRequest()->getBaseUrl().'/application/formulario/registro/1');
}else
{
//zona del formulario
$form=new Formularios("form");
$id = (int) $this->params()->fromRoute('id', 0);
$valores=array
(
"titulo"=>"Registro de Usuario",
"form"=>$form,
'url'=>$this->getRequest()->getBaseUrl(),
'id'=>$id
);
return new ViewModel($valores);
}
}
}
this is my form code with validator
class Formularios extends Form
{
public function __construct($name = null)
{
parent::__construct($name);
$this->add(array(
'name' => 'name',
'required' => true,
'allow_empty' => false,
'options' => array(
'label' => 'Nombre Completo',
),
'attributes' => array(
'type' => 'text',
'class' => 'input'
),
'filters' => [ ['name' => 'StringTrim'], ],
'validators' => array(
array(
'name' => 'NotEmpty',
'options' => array(
'messages' => array(
\Zend\Validator\NotEmpty::IS_EMPTY => 'Ingrese Nombres.',
))))
));
$this->add(array(
'name' => 'lastname',
'required' => true,
'options' => array(
'label' => 'Apellido',
),
'attributes' => array(
'type' => 'text',
'class' => 'input'
),
'validators' => array(
array(
'name' => 'NotEmpty',
'options' => array(
'messages' => array(
\Zend\Validator\NotEmpty::IS_EMPTY => 'Ingrese Apellidos.',
))))
));
Thanks in advance
First problem.
$data = $this->request->getPost(); should be $data = $this->getRequest()->getPost();
Second problem is that you call your validators direclty when you build your form in the view, which is wrong. The right way to do is via an inputFilter. Now, there are many ways to to this, for example: with or without a factory called from your model or via the for class with a form element manager
I will show you the model way with a factory since it's easier for new comers.
namespace MyModule\Model;
use Zend\InputFilter\InputFilter;
use Zend\InputFilter\Factory as InputFactory;
use Zend\InputFilter\InputFilterAwareInterface;
use Zend\InputFilter\InputFilterInterface;
class MyModel implements InputFilterAwareInterface
{
/**
* #var null $_inputFilter inputFilter
*/
private $_inputFilter = null;
// some more code like exhnageArray get/set method
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([
'name' => 'id',
'required' => false,
'filters' => [
['name' => 'Int'],
],
])
);
$inputFilter->add(
$factory->createInput([
"name"=>"title",
"required" => true,
'filters' => [
['name' => 'StripTags'],
['name' => 'StringTrim'],
],
'validators' => [
['name' => 'NotEmpty'],
[
'name' => 'StringLength',
'options' => [
'encoding' => 'UTF-8',
'min' => 1,
'max' => 200,
],
],
],
])
);
$inputFilter->add(
$factory->createInput([
"name"=>"text",
"required" => true,
'filters' => [
['name' => 'StripTags'],
['name' => 'StringTrim'],
],
'validators' => [
['name' => 'NotEmpty'],
[
'name' => 'StringLength',
'options' => [
'encoding' => 'UTF-8',
'min' => 1,
],
],
],
])
);
$this->inputFilter = $inputFilter;
}
return $this->inputFilter;
}
}
Third proble. DO NOT EVER use serviceManager in controller. It's a really really really bad practice. Instead use a factory.

How to write router for this url "/products/{id}/payment_plans/{plan-id}"

My current route file:
<?php
return array(
'controllers' => array(
'invokables' => array(
'Customers\Controller\Customers' => 'Customers\Controller\CustomersController',
),
),
// The following section is new` and should be added to your file
'router' => array(
'routes' => array(
'customers' => array(
'type' => 'Segment',
'options' => array(
'route' => '/customers[/:action][/:id]',
'constraints' => array(
'id' => '[0-9]+',
),
'defaults' => array(
'controller' => 'Customers\Controller\Customers',
),
),
),
),
),
'view_manager' => array(
'strategies' => array(
'ViewJsonStrategy',
),
),
);
How to function to get data
My current controller:
<?php
namespace Products\Controller;
// <-- Add this import
use Zend\Mvc\Controller\AbstractRestfulController;
use Products\Model\Products; // <-- Add this import
use Products\Form\ProductsForm; // <-- Add this import // <-- Add this import
use Zend\View\Model\JsonModel;
use Zend\Db\TableGateway\TableGateway;
class ProductsController extends AbstractRestfulController {
protected $productsTable;
private $returnMsg = array();
public function getList($data) {
$data = array();
$results = $this->getproductsTable()->select();
foreach ($results as $result) {
$data[] = $result;
}
return new JsonModel(array(
'data' => $data,
));
}
public function get($data) {
// $products = $this->getProductsTable()->getProducts($id);
return new JsonModel(array(
'data' => '',
));
}
public function payment_plans($data) {
// $products = $this->getProductsTable()->getProducts($id);
return new JsonModel(array(
'data' => '',
));
}
public function create($data) {
$form = new ProductsForm();
$products = new Products();
$form->setInputFilter($products->getInputFilter());
$form->setData($data);
if ($form->isValid()) {
$returnMsg = 'ok';
$products->exchangeArray($form->getData());
date_default_timezone_set("UTC");
$cdate = date("Y-m-d H:i:s", time());
$data = array(
'prd_main_id' => (isset($data['prd_main_id'])) ? $data['prd_main_id'] : null,
'prd_main_title' => (isset($data['prd_main_title'])) ? $data['prd_main_title'] : null,
'prd_main_description' => (isset($data['prd_main_description'])) ? $data['prd_main_description'] : null,
'prd_main_created_at' => (isset($cdate)) ? $cdate : null,
);
$this->getproductsTable()->insert($data);
/*
$cus_email = $data['cus_email'];
$results = $this->getCustomersTable()->select(array('cus_email' => $cus_email));
foreach ($results as $result) {
$datar[] = $result;
}
if (empty($datar)) {
$this->getCustomersTable()->insert($data);
$cus_email = $data['cus_email'];
$resultsv = $this->getCustomersTable()->select(array('cus_email' => $cus_email));
foreach ($resultsv as $resultv) {
$datav = $resultv;
}
$returnMsg = $datav;
} else {
$returnMsg = array('errors' => "email address already exists ! ");
}
*/
} else {
$returnMsg = 'ofgk';
}
return new JsonModel(array(
$data,
));
}
public function update($id, $data) {
$data['id'] = $id;
$products = $this->getProductsTable()->getProducts($id);
$form = new ProductsForm();
$form->bind($products);
$form->setInputFilter($products->getInputFilter());
$form->setData($data);
if ($form->isValid()) {
$id = $this->getProductsTable()->saveProducts($form->getData());
}
return new JsonModel(array(
'data' => $this->get($id),
));
}
public function delete($id) {
$this->getProductsTable()->deleteProducts($id);
return new JsonModel(array(
'data' => 'deleted',
));
}
public function getproductsTable() {
if (!$this->productsTable) {
$this->productsTable = new TableGateway('products', $this->getServiceLocator()->get('Zend\Db\Adapter\Adapter'));
}
return $this->productsTable;
}
}
'name' => array(
'type' => 'Segment',
'options' => array(
'route' => '/products[/[:id]]/payment_plans[/[:payment_id]]',
'defaults' => array(
'__NAMESPACE__' => 'Template\Controller',
'id' => '[a-zA-Z][a-zA-Z0-9_-]*',
'payment_id' => '[a-zA-Z][a-zA-Z0-9_-]*',
),
),

zf2 The supplied parameters to DbTable failed to produce a valid sql statement, please check table and column names for validity

On authentication I am getting an error message
"The supplied parameters to DbTable failed to produce a valid sql statement, please check table and column names for validity."
my login controller code is
$form= new login();
$request=$this->getRequest();
if ($request->isPost())
{
$formValidator = new rotaryfilter();
$post=$request->getPost();
$form->setInputFilter($formValidator->getInputFilter());
$form->setData($request->getPost());
if($form->isValid())
{
$formValidator->exchangeArray($form->getData());
$dbAdapter = $this->serviceLocator->get('Zend\Db\Adapter\Adapter');
$authAdapter = new DbTable($dbAdapter,'Login','username','pwd');
$authAdapter->setIdentity($formValidator->username)
->setCredential($formValidator->pwd);
//->setCredentialTreatment('MD5(?)');
$authService = $this->serviceLocator->get('auth_service');
$authService->setAdapter($authAdapter);
$result = $authService->authenticate();
if($result->isValid())
{
echo 'valid';
exit();
}
else { echo 'invalid';exit();}
}
}
return array('form'=> $form);
and my module.php contains
public function getServiceConfig()
{
return array(
'factories' => array(
'auth_service' => function ($sm) {
$authService = new AuthenticationService(new SessionStorage('auth'));
return $authService;
},
'General\Model\Login' => function($sm) {
$tableGateway = $sm->get('LoginGateway');
$table = new Login($tableGateway);
return $table;
},
'LoginGateway' => function ($sm) {
$dbAdapter = $sm->get('Zend\Db\Adapter\Adapter');
$resultSetPrototype = new ResultSet();
$resultSetPrototype->setArrayObjectPrototype(new rotaryfilter());
return new TableGateway('Login', $dbAdapter, null, $resultSetPrototype);
},
),);
}
This may seems old but I was able to solve this error. This error is caused from you MySQL version.
This one works for me. All you need to do is to remove the driver_options from your db setup, this code is usually located at your global.php or .local.php from your Config file.
Change FROM:
'db' => array(
'driver' => 'Pdo_Mysql',
'dsn' => 'mysql:dbname=dbName;host=localhost',
'username' => 'dbUser',
'password' => 'dbPass',
'driver_options' => array(
PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES \'UTF8\''
),
),
TO
'db' => array(
'driver' => 'Pdo_Mysql',
'dsn' => 'mysql:dbname=dbName;host=localhost',
'username' => 'dbUser',
'password' => 'dbPass',
),
Thank you. This solution solved my problem.

Resources