I have a problem with inserting Records into a DB using Zend FrameWork 2.
There are no records saved into the DB when submitting the Form and also no Error Messages Appear, just the Confirmation Message telling me that it << Registered Successfully >>
Here is my code, thanks in advance:
// App/config/autoload/global.php
return array(
'db' => array(
'driver' => 'pdo',
'dsn' => 'mysql:dbname=zf_app;host=localhost;port:8080',
'username' => 'zf_user',
'password' => 'zf_pass',
'driver_options' => array(
PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES \'UTF8\''
),
),
'service_manager' => array(
'factories' => array(
'Zend\Db\Adapter\Adapter' =>'Zend\Db\Adapter\AdapterServiceFactory',
),
),
);
#################################################################
//App\module\Users\src\Users\Model\Usertable.php
<?php
namespace Users\Model;
use Zend\Db\Adapter\Adapter;
use Zend\Db\ResultSet\ResultSet;
use Zend\Db\TableGateway\TableGateway;
class UserTable
{
protected $tableGateway ;
public function __construct(TableGateway $tableGateway)
{
$this->tableGateway = $tableGateway;
}
public function saveUser(User $user)
{
$data = array(
'email' => $user->email ,
'name' => $user->name,
'password' => $user->password,
);
$id = (int)$user->id ;
if($id == 0)
{
$this->tableGateway->insert($data);
} else {
if($this->getUser($id))
{
$this->tableGateway->update($data , array('id' => $id));
} else {
throw new \Exception("User ID does not Exist ");
}
}
}
public function getUser($id)
{
$id = (int)$id;
$rowset = $this->tableGateway->select(array('id' => $id ));
$row = $rowset->current();
if(!$row)
{
throw new \Exception("Could not Find row $id ");
}
return $row ;
}
}
##########################################################
// App\module\Users\src\Users\Controller\RegisterController.php
<?php
namespace Users\Controller;
use Zend\Mvc\Controller\AbstractActionController;
use Zend\View\Model\ViewModel;
use Users\Form\RegisterForm;
use Users\Form\RegisterFilter;
use Zend\Db\Adapter\Adapter;
class RegisterController extends AbstractActionController
{
public function indexAction()
{
$form = new RegisterForm();
$viewModel = new ViewModel(array('form' => $form));
return $viewModel;
}
public function confirmAction()
{
$viewModel = new ViewModel();
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 createUser(array $data)
{
$sm = $this->getServiceLocator();
$dbAdapter = $sm->get('Zend\Db\Adapter\Adapter');
$resultSetPrototype = new \Zend\Db\ResultSet\ResultSet();
$resultSetPrototype->setArrayObjectPrototype(new \Users\Model\User);
$tableGateway = new \Zend\Db\TableGateway\TableGateway('user' , $dbAdapter , null , $resultSetPrototype);
$user = new User();
$user->exchangeArray($data);
$userTable = new UserTable($tableGateway);
$userTable->saveUser($user);
$this->createUser($form->getData());
return true;
}
}
Create // App/config/autoload/local.php
// App/config/autoload/local.php
return array(
'db' => array(
'username' => "zf_user",
'password' => "zf_pass",
)
);
and remove username and password from global.php
What is the User in public function saveUser(User $user) ? You didn't use User file.
Related
I am new to zend framework2.
I got the error.
An exception was raised while creating "UserTable"; no instance returned.
Please look my code.
Login\Model\UserTable.php
protected $tableGateway;
public function __construct(TableGateway $tableGateway)
{
$this->tableGateway = $tableGateway;
}
public function fetchAll()
{
$resultSet = $this->tableGateway->select();
return $resultSet;
}
Login\Module.php
public function getServiceConfig()
{
return array(
'factories' => array(
'UserTable' => function($serviceManager) {
$tableGateway = $serviceManager->get('UserTableGateway');
return new UserTable($tableGateway);
},
'UserTableGateway' => function ($serviceManager) {
$dbAdapter = $serviceManager->get('Zend\Db\Adapter\Adapter');
$resultSetPrototype = new ResultSet();
$resultSetPrototype->setArrayObjectPrototype(NULL);
return new TableGateway('user', $dbAdapter, NULL, $resultSetPrototype);
}
)
);
}
Login\src\Login\Controller\LoginController.php
public function getAction()
{
$serviceManager = $this->getServiceLocator();
$userTable = $serviceManager->get('UserTable');
$user = $userTable->fetchAll();
return $this->redirect()->toRoute('home', ['data' => $user]);
}
local.php
return array(
'db' => array(
'dsn' => 'mysql:dbname=album; host=localhost',
'username' => 'root',
'password' => 'root',
),
'service_manager' => array(
'factories' => array(
'Zend\Db\Adapter\Adapter'
=> 'Zend\Db\Adapter\AdapterServiceFactory',
),
)
);
when I just redirect to home in getAction() in controller, it working fine.
I couldn't get solution for this.
can anyone help me out.
Thanks in advance.
NOTE: please comment, if you need more details.
Hi I am having errors trying to inject dependencies on my controllers.
Warning: Missing argument 1 for User\Controller\LoginController::__construct(), called in /var/www/html/engsvc_dev/vendor/zendframework/zendframework/library/Zend/ServiceManager/AbstractPluginManager.php on line 170 and defined in /var/www/html/engsvc_dev/module/User/src/User/Controller/LoginController.php on line 23
Module.php
public function getControllerConfig(){
return array(
'factories' => array(
'Login' => function ($sm) {
$locator = $sm->getServiceLocator();
$controller = new LoginController($locator->get("Config"));
return $controller;
},
),
);
}
Controller
class LoginController extends AbstractActionController{
protected $globalConfig;
protected $UserModuleSetup;
public function __construct($config){
}
module.config.php
"invokables" => array(
"User" => "User\Controller\LoginController",
"Login" => "User\Controller\LoginController"
),
Module.php
public function getControllerConfig(){
return array(
'factories' => array(
'Login' => function ($sm) {
$locator = $sm->getServiceLocator();
$controller = new User\Controller\LoginController($locator->get("Config"));
return $controller;
},
),
);
}
Controller
class LoginController extends AbstractActionController{
protected $globalConfig;
protected $UserModuleSetup;
public function __construct($config){
}
module.config.php
"invokables" => array(
"User" => "User\Controller\LoginController",
),
How can I setup default for Text element in ZF2 Forms?
I tried the following:
In the view file. This does not get to data, and is not saved:
if($form->get('agencyName')->getValue() === '')
$form->get('agencyName')->setValue('Virtual Field Practicum');
This affects neither view, nor DB:
$this->add(array(
'name' => 'agencyName',
'options' => array(
'label' => 'Agency Name',
),
'attributes' => array(
'disabled' => 'disabled',
'value' => 'Virtual Field Practicum',
)
));
I also tried to modify entity in two ways, but it did not affect anything:
public function __construct()
{
//set default agency name
$this->agencyName = 'Virtual Field Practicum';
}
OR:
public function setAgencyName($agencyName)
{
if ($agencyName === '')
$this->agencyName = 'Virtual Field Practicum';
else
$this->agencyName = $agencyName;
return $this;
}
Edit 1
Adding my generic actions to the post:
1) This one is responsible to load the forms, and process non-ajax calls:
public function editTabAction()
{
$buildName = $this->params()->fromRoute('buildName', 'unknown');
if ($buildName == 'unknown') {
$buildName = $this->params()->fromPost('buildName', 'unknown');
if ($buildName == 'unknown') {
trigger_error('Could not retrieve build name for ' . $buildName . ' entity for this form!');
}
}
//extract parameter from dispatch command
$studEvalId = (int)$this->params()->fromRoute('studEvalId', 0);
if ($studEvalId == 0) {
//extract parameter from the form submission
$studEvalId = (int)$this->params()->fromPost('studEvalId', 0);
if ($studEvalId == 0) {
return $this->notFoundAction();
}
}
$data = $this->getEntity($buildName, $studEvalId);
// Get your ObjectManager from the ServiceManager
$objectManager = $this->getEntityManager();
// get from from FormElementManager plugin
//forms are defined in Module.php
$formName = $buildName . "Form";
$sl = $this->getServiceLocator();
$form = $sl->get('FormElementManager')->get($formName);
$form->setHydrator(new DoctrineHydrator($objectManager ));
$form->setObject($this->getEntityInstanceFromBuildName($buildName));
$form->bind($data);
//set class and Id for buttons like SaveChanges to reference it
$form->setAttribute('class', "studentFormsClass_$studEvalId");
$form->setAttribute('id', "studentFormsId_$studEvalId" . "_$buildName");
//set buildName to the form
$form->get('buildName')->setAttribute('value', $buildName);
$request = $this->getRequest();
if ($request->isPost()) {
$formValidatorName = "OnlineFieldEvaluation\Form\\" . $buildName . "FormValidator";
$formValidator = new $formValidatorName();
$form->setInputFilter($formValidator->getInputFilter());
$form->setData($request->getPost());
if ($form->isValid()) {
$this->savetodb($form->getData(), $buildName);
// Redirect to list of forms
return false;
} else {
foreach ($form->getMessages() as $messageId => $message) {
echo '<pre>';
echo "Validation failure '$messageId':";
print_r($message);
echo '</pre>';
}
}
}
$view = new ViewModel(array(
'studEvalId' => $studEvalId,
'buildName' => $buildName,
'form' => $form,
));
$view->setTemplate('online-field-evaluation/tabs/edit' . $buildName . '.phtml');
return $view;
}
2) This one is responsible for ajax calls:
public function validatepostajaxAction()
{
$request = $this->getRequest();
$response = $this->getResponse();
$buildName = $this->params()->fromRoute('buildName', 'unknown');
if ($buildName == 'unknown') {
$buildName = $this->params()->fromPost('buildName', 'unknown');
if ($buildName == 'unknown') {
trigger_error('Could not retrieve build name for ' . $buildName . ' entity for this form!');
}
}
//extract parameter from dispatch command
$studEvalId = (int)$this->params()->fromRoute('studEvalId', 0);
if ($studEvalId == 0) {
//extract parameter from the form submission
$studEvalId = (int)$this->params()->fromPost('studEvalId', 0);
if ($studEvalId == 0) {
return $this->notFoundAction();
}
}
$data = $this->getEntity($buildName, $studEvalId);
$objectManager = $this->getEntityManager();
$formName = $buildName . "Form";
$sl = $this->getServiceLocator();
$form = $sl->get('FormElementManager')->get($formName);
$form->setHydrator(new DoctrineHydrator($objectManager ));
$entityName = 'OnlineFieldEvaluation\Entity\\' . $buildName;
$form->setObject(new $entityName());
$form->bind($data);
//set class and Id for buttons like SaveChanges to reference it
$form->setAttribute('class', "studentFormsClass_$studEvalId");
$form->setAttribute('id', "studentFormsId_$studEvalId" . "_$buildName");
//set buildName to the form
$form->get('buildName')->setAttribute('value', $buildName);
$messages = array();
if ($request->isPost()) {
$formValidatorName = "OnlineFieldEvaluation\Form\\" . $buildName . "FormValidator";
$formValidator = new $formValidatorName();
$form->setInputFilter($formValidator->getInputFilter());
$form->setData($request->getPost());
if (!$form->isValid()) {
$errors = $form->getMessages();
foreach ($errors as $key => $row) {
if (!empty($row) && $key != 'submit') {
foreach ($row as $keyer => $rower) {
//save error(s) per-element that
//needed by Javascript
$messages[$key][] = $rower;
}
}
}
}
if (!empty($messages)) {
$response->setContent(
\Zend\Json\Json::encode(
array('status' => 'error',
'messages' => (array) $messages,
'buildName' => $buildName,
'studEvalId' => $studEvalId
)));
} else {
//save to db <span class="wp-smiley wp-emoji wp-emoji-wink" title=";)">;)</span>
$this->savetodb($form->getData(), $buildName);
$response->setContent(
\Zend\Json\Json::encode(
array(
'status' => 'success',
'messages' => 'Successfuly saved.',
'buildName' => $buildName,
'studEvalId' => $studEvalId
)
));
}
}
return $response;
}
To setup a default value for an element, simply do the following:
Open controller's action, that renders desired view
Instantiate a form, get the element by its name and do call setValue() on that
That looks like as following:
public function addAction()
{
$form = new YourAgencyForm();
$form->get('agencyName')->setValue('Virtual Field Practicum');
....
It's really that simple
Module :
public function getServiceConfig() {
return array(
'factories' => array(
// 'user' table-------------------------------------
'Album\Model\AlbumTable\dbtable=user' => function($sm) {
$tableGateway = $sm->get('UserTableGateway');
$table = new SignupTable($tableGateway);
return $table;
},
'UserTableGateway' => function ($sm) {
$dbAdapter = $sm->get('Zend\Db\Adapter\Adapter');
$resultSetPrototype = new ResultSet();
$resultSetPrototype->setArrayObjectPrototype(new Signup());
return new TableGateway('user', $dbAdapter, null, $resultSetPrototype);
},
),
);
}
Now how can I call my ‘dbadapter’ in anywhere in the model while I need it for
new \Zend\Validator\Db\RecordExists(
array(
'table' => 'user',
'field' => 'username',
'adapter' => $dbadapter
)
)
please tell me the way to call adapter in anywhere.
-thanks.
Edit :
I followed this 'Get default zend db adapter in table model' thread and did the following in my ‘model’,
<?php
namespace Application\Model;
use Zend\InputFilter\InputFilter;
use Zend\InputFilter\InputFilterAwareInterface;
use Zend\InputFilter\InputFilterInterface;
use Zend\Validator;
class Signup implements InputFilterAwareInterface {
public $username;
protected $inputFilter;
protected $serviceLocator;
protected $dbAdapter;
public function getServiceLocator() {
return $this->serviceLocator;
}
public function setServiceLocator(Zend\ServiceManager\ServiceLocatorInterface $serviceLocator) {
$this->serviceLocator = $serviceLocator;
return $this;
}
public function exchangeArray($data) {
$this->username = (!empty($data['username'])) ? $data['username'] : null;
$this->password = (!empty($data['password'])) ? $data['password'] : null;
$this->email = (!empty($data['email'])) ? $data['email'] : null;
}
public function getArrayCopy() {
return get_object_vars($this);
}
public function setInputFilter(InputFilterInterface $inputFilter) {
throw new \Exception("Not used");
}
public function getInputFilter() {
$this->$dbAdapter = $this->getServiceLocator()->get('Zend\Db\Adapter\Adapter');
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' => 'NotEmpty',
'options' => array(
'messages' => array(
\Zend\Validator\NotEmpty::IS_EMPTY => 'Username required',
),
),
),
new \Zend\Validator\Db\RecordExists(
array(
'table' => 'user',
'field' => 'username',
'adapter' => $this->dbAdapter,
)
)
),
));
$this->inputFilter = $inputFilter;
}
return $this->inputFilter;
}
}
but I got this error,
Fatal error: Call to a member function get() on a non-object in F:\xampp\htdocs\zendtest\module\Application\src\Application\Model\Signup.php on line 41
Why is that ?
I made it like the following,
Module :
<?php
namespace Application;
use Zend\Mvc\ModuleRouteListener;
use Zend\Mvc\MvcEvent;
use Application\Model\Signup;
use Application\Model\SignupTable;
use Zend\Db\ResultSet\ResultSet;
use Zend\Db\TableGateway\TableGateway;
class Module {
public function onBootstrap(MvcEvent $e) {
$e->getApplication()->getServiceManager()->get('translator');
$eventManager = $e->getApplication()->getEventManager();
$moduleRouteListener = new ModuleRouteListener();
$moduleRouteListener->attach($eventManager);
}
public function getConfig() {
return include __DIR__ . '/config/module.config.php';
}
public function getAutoloaderConfig() {
return array(
'Zend\Loader\StandardAutoloader' => array(
'namespaces' => array(
__NAMESPACE__ => __DIR__ . '/src/' . __NAMESPACE__,
),
),
);
}
public function getServiceConfig() {
return array(
'factories' => array(
'dbAdapter\dbtable=user' => function($sm) {
$dbAdapterr = $sm->get('Zend\Db\Adapter\Adapter');
return $dbAdapterr;
},
),
);
}
}
Controller :
<?php
namespace Application\Controller;
use Zend\Mvc\Controller\AbstractActionController;
use Zend\View\Model\ViewModel;
use Application\Model\Signup;
use Application\Form\SignupForm;
class IndexController extends AbstractActionController {
protected $userTablee;
public function getSignTable($table, $object) {
if (!$this->$object) {
$sm = $this->getServiceLocator();
$this->$object = $sm->get($table);
}
return $this->$object;
}
public function indexAction() {
return new ViewModel();
}
public function signupAction() {
$form = new SignupForm();
$form->get('submi')->setValue('Submit');
$request = $this->getRequest();
if ($request->isPost()) {
$album = new Signup();
$t = $this->getSignTable('dbAdapter\dbtable=user', 'userTablee'); // its to get adapter from Module via getSignTable()
$form->setInputFilter($album->getInputFilter($t)); // passes adapter to Model
$form->setData($request->getPost());
if ($form->isValid()) {
// code goes here
}
}
}
}
Model :
<?php
namespace Application\Model;
use Zend\InputFilter\InputFilter;
use Zend\InputFilter\InputFilterAwareInterface;
use Zend\InputFilter\InputFilterInterface;
use Zend\Validator;
class Signup implements InputFilterAwareInterface {
public $username;
public $password;
public $email;
protected $inputFilter;
protected $adapter;
public function exchangeArray($data) {
$this->username = (!empty($data['username'])) ? $data['username'] : null;
$this->password = (!empty($data['password'])) ? $data['password'] : null;
$this->email = (!empty($data['email'])) ? $data['email'] : null;
}
public function getArrayCopy() {
return get_object_vars($this);
}
public function setInputFilter(InputFilterInterface $inputFilter) {
throw new \Exception("Not used");
}
public function getInputFilter($adapter = null) { // receives adapter here
$this->adapter = $adapter;
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' => 'NotEmpty',
'options' => array(
'messages' => array(
\Zend\Validator\NotEmpty::IS_EMPTY => 'Username required',
),
),
),
new \Zend\Validator\Db\NoRecordExists(
array(
'table' => 'user',
'field' => 'username',
'adapter' => $this->adapter, // this line for adapter
'messages' => array(
\Zend\Validator\Db\AbstractDb::ERROR_RECORD_FOUND => 'Username already exists',
),
)
)
),
));
$this->inputFilter = $inputFilter;
}
return $this->inputFilter;
}
}
I'm learning ZF2 by starting write a simple UserAuth Plugin for authentication but have got the exceptions:
An exception was raised while creating "userAuth"; no instance returned
Previous exceptions:
The supplied or instantiated driver object does not implement Zend\Db\Adapter\Driver\DriverInterface
error at this line: $sm->get('Zend\Db\Adapter\Adapter')
The following is my User\Module.php
class Module {
public function onBootstrap(MvcEvent $e)
{
$e->getApplication()->getServiceManager()->get('translator');
$eventManager = $e->getApplication()->getEventManager();
$moduleRouteListener = new ModuleRouteListener();
$moduleRouteListener->attach($eventManager);
}
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 getConfig()
{
return include __DIR__ . '/config/module.config.php';
}
public function getServiceConfig()
{
return array(
'invokables' => array(
),
'factories' => array(
'User\Form\Signin' => function($sm) {
$form = new Form\Signin();
$form->setInputFilter(new Form\SigninFilter);
return $form;
},
'User\Auth\Service' => function ($sm) {
return new \Zend\Authentication\AuthenticationService(
new \Zend\Authentication\Storage\Session(),
new \Zend\Authentication\Adapter\DbTable($sm->get('Zend\Db\Adapter\Adapter'))
);
},
),
);
}
public function getControllerPluginConfig()
{
return array(
'factories' => array(
'UserAuth' => function ($sm) {
$sl = $sm->getServiceLocator();
$authService = $sl->get('User\Auth\Service');
$authAdapter = new \Zend\Authentication\Adapter\DbTable($sm->get('Zend\Db\Adapter\Adapter'));
$controllerPlugin = new Controller\Plugin\UserAuth();
$controllerPlugin->setAuthService($authService);
$controllerPlugin->setAuthAdapter($authAdapter);
return $controllerPlugin;
},
),
);
}
}
Please help me to fix it.
Add:
use Zend\Db\Adapter\Adapter;
to the top of Controller\Plugin\UserAuth.php
and:
extends Adapter
after:
class UserAuth
in the same file. That will at least get you going in the right direction.