non-object error on Doctrine 2 entity manager object - zend-framework

I'm trying to learn the zend framework by reading through a book. So far all the code in it has worked, but now I'm having trouble authenticating users. The book suggests doing this through an action helper and doctrine 2's entity managers.
here's the code i'm using for this
my authenticate helper class...
public function init()
{
// Initialize the errors array
Zend_Layout::getMvcInstance()->getView()->errors = array();
$auth = Zend_Auth::getInstance();
$em = $this->getActionController()->getInvokeArg('bootstrap')->getResource('entityManager');
if ($auth->hasIdentity()) {
$identity = $auth->getIdentity();
if (isset($identity)) {
$user = $em->getRepository('Entities\User')->findOneByEmail($identity);
Zend_Layout::getMvcInstance()->getView()->user = $user;
}
}
}
the entity repository function...
public function findOneByEmail($email)
{
$rsm = new ResultSetMapping;
$rsm->addEntityResult('Entities\User', 'a');
$rsm->addFieldResult('a', 'id', 'id');
$rsm->addFieldResult('a', 'email', 'email');
$rsm->addFieldResult('a', 'fname', 'fname');
$query = $this->_em->createNativeQuery(
'SELECT a.id, a.fname, a.email FROM users a
WHERE a.email = :email',
$rsm
);
$query->setParameter('email', $email);
return $query->getResult();
}
On the page view, i'm using the following code to check that the user is logged in:
<?php
if($this->user){
?>Welcome back, <?php echo $this->user->fname; ?> • Logout<?php
} ?>
the if condition passes when i'm logged in, but it won't print the user's name.
here's the error message I get on it:
Notice: Trying to get property of non-object in C:\Program Files (x86)\Zend\Apache2\htdocs\dev.test.com\application\views\scripts\user\index.phtml on line 3
Can anyone help me fix this?

I think part of the problem is here:
if (isset($identity)) {
$user = $em->getRepository('Entities\User')->findOneByEmail($identity);
Zend_Layout::getMvcInstance()->getView()->user = $user;
}
It looks like findOneByEmail expects the email address as the parameter but the whole identity object is being passed.
That probably causes return $query->getResult(); to return null or false so $view->user is not an object and has no property fname.
I think in findOneByEmail you need to do something like $user = $em->getRepository('Entities\User')->findOneByEmail($identity->email); where $identity->email is the property that contains the email address.

Related

sugarcrm: unable to call login from custom soap service by extending existing webservice

I am following this tutorial to extend the Sugarcrm webservice to define the new service for my custom module.
Problem: But, as a preliminary check, I tried to call the existing login service and that itself fails. Please help in pointing where the issue is. I am stuck.
Tutorial I am following: http://support.sugarcrm.com/02_Documentation/04_Sugar_Developer/Sugar_Developer_Guide_6.5/02_Application_Framework/Web_Services/06_Extending_Web_Services/
As mentioned in the tutorial, I created the following files in the folder, custom/service/v4_1_custom
registry.php
<?php
require_once('service/v4_1/registry.php');
class registry_v4_1_custom extends registry_v4_1
{
protected function registerFunction()
{
parent::registerFunction();
$this->serviceClass->registerFunction('my_get_orders',
array(
'session' => 'xsd:string',
'module_name' => 'xsd:string',
'id' => 'xsd:string',
),
array(
'return' => 'xsd:string',
)
);
}
}
?>
soap.php
<?php
if(!defined('sugarEntry'))define('sugarEntry', true);
chdir('../../..');
require_once('SugarWebServiceImplv4_1_custom.php');
$webservice_class = 'SugarSoapService2';
$webservice_path = 'service/v2/SugarSoapService2.php';
$registry_class = 'registry_v4_1_custom';
$registry_path = 'custom/service/v4_1_custom/registry.php';
$webservice_impl_class = 'SugarWebServiceImplv4_1_custom';
$location = 'custom/service/v4_1_custom/soap.php';
require_once('service/core/webservice.php');
?>
SugarWebServiceImplv4_1_custom.php
<?php
if(!defined('sugarEntry'))define('sugarEntry', true);
require_once('service/v4_1/SugarWebServiceImplv4_1.php');
class SugarWebServiceImplv4_1_custom extends SugarWebServiceImplv4_1
{
/*
* Returns the id if authenticated
*
* #param id
* #return string $session - false if invalid.
*
*/
function my_get_orders($session, $module_name, $id)
{
$GLOBALS['log']->info('Begin: SugarWebServiceImplv4_1_custom->my_get_orders');
$error = new SoapError();
//authenticate
if (!self::$helperObject->checkSessionAndModuleAccess($session, 'invalid_session', '', '', '', $error))
{
$GLOBALS['log']->info('End: SugarWebServiceImplv4_1_custom->my_get_orders.');
return false;
}
return $id;
}
}
?>
My webservice client for testing the webservice: SoapTest.php
SoapTest.php
<?php
if(!defined('sugarEntry'))define('sugarEntry', true);
require_once('../include/nusoap/nusoap.php'); //must also have the nusoap code on the ClientSide.
$user_name ='myuser';
$user_password = 'mypassword';
$hostname = 'http://127.0.0.1/sugarcrm/custom/service/v4_1_custom/soap.php?wsdl';
// Create the SOAP client instance
$soapclient = new nusoapclient($hostname, true);
// Login to the server
echo '<b>LOGIN:</b><BR>';
$result = $soapclient->call('login',array('user_auth'=>array('user_name'=>$user_name,'password'=>md5($user_password), 'version'=>'.01'), 'application_name'=>'SoapTest'));
echo '<BR><BR><b>HERE IS RESULT:</b><BR>';
echo print_r($result);
echo var_dump($result);
$session = $result['id'];
echo "sessionid is ".$session;
?>
Expected Result: Since I am calling the login, i expect to see the sessionid.
Note: I am not calling the custom method my_get_orders as the login itself fails. So i like to fix it first.
Actual Result: [while invoking http://127.0.0.1/sugarcrm/prash/SoapTest.php]
HERE IS RESULT:
1
boolean false
sessionid is
I put the same set of files under service/custom [ The existing versions are directly under service/ eg : service/v4_1 ].
Now it works, so earlier it was the case of file path resolving issue.

Zend Form Registration with

I am new in Zend.
I have tried to create registration form in Zend.
I have get an array of form but it return false.
It returns me every time bye .
I don't know why???
It's Simple:
First, create your registration form under application/forms or use zend tool
zf enable form
zf create form registration
this will create a file under application/forms entitled Registration.php
class Application_Form_Registration extends Zend_Form
{
public function init()
{
$firstname = $this->createElement('text','firstname');
$firstname->setLabel('First Name:')
->setRequired(false);
$lastname = $this->createElement('text','lastname');
$lastname->setLabel('Last Name:')
->setRequired(false);
$email = $this->createElement('text','email');
$email->setLabel('Email: *')
->setRequired(false);
$username = $this->createElement('text','username');
$username->setLabel('Username: *')
->setRequired(true);
$password = $this->createElement('password','password');
$password->setLabel('Password: *')
->setRequired(true);
$confirmPassword = $this->createElement('password','confirmPassword');
$confirmPassword->setLabel('Confirm Password: *')
->setRequired(true);
$register = $this->createElement('submit','register');
$register->setLabel('Sign up')
->setIgnore(true);
$this->addElements(array(
$firstname,
$lastname,
$email,
$username,
$password,
$confirmPassword,
$register
));
}
}
This is a simple form with limited validation (only validation for fields that are required!)
Then you have to render the form in a view using the corresponding action:
as example in your UserController add action called
public function registerAction() {
//send the form to the view (register)
$userForm = new Application_Form_Registration();
$this->view->form = $userForm;
//check if the user entered data and submitted it
if ($this->getRequest()->isPost()) {
//check the form validation if not valid error message will appear under every required field
if ($userForm->isValid($this->getRequest()->getParams())) {
//send data to the model to store it
$userModel = new Application_Model_User();
$userId = $userModel->addUser($userForm->getValues());
}
}
}
The last two, is to render the form in the view called register
using
<?= $this->form ?>
and add method in your model called addUser() to handle the insertion of data into the database

Uncaught exception 'Zend_Locale_Exception' with message 'The locale '' is no known locale'

i'm trying to make the translation of a website in zend framework, but, given that is the first time i use this framework, i'm having some problems. The last one is the one that gives me the error you're seeing as a title here.
I've set two important methods in the Bootstrap file:
protected function _initLocale()
{
$session = new Zend_Session_Namespace('ttb.l10n');
if ($session->locale)
{
$locale = new Zend_Locale($session->locale);
}
if ($locale === null)
{
try
{
$locale = new Zend_Locale('browser');
}
catch (Zend_Locale_Exception $e)
{
$locale = new Zend_Locale('en');
}
}
$registry = Zend_Registry::getInstance();
$registry->set('Zend_Locale', $locale);
}
protected function _initTranslate()
{
$translate = new Zend_Translate('array',
APPLICATION_PATH . '/../languages/',
'null',
array('scan' => Zend_Translate::LOCALE_FILENAME,
'disableNotices' => 0));
$registry = Zend_Registry::getInstance();
$registry->set('Zend_Translate', $translate);
return $translate;
}
The problem is that if I want the right translation in my pages i have to set the locale to the $translate variable and set it for every view I'll show to the user. The website has only one page, so i assumed the variable $translate would be avaliable in every action, and i changed the init method of the indexController.php:
public function init()
{
/* Initialize action controller here */
$registry = Zend_Registry::getInstance();
//The following is for the links that set the local language manually
$this->view->locale = $this->_getParam('locale');
if(!$this->view->locale){
$this->view->locale = $registry->get('Zend_Locale');
}
$translate->setLocale($locale);
}
The error i'm getting is the following (from zend server):
Function Name Zend_Application::bootstrap
Error Type E_ERROR
Source File /usr/local/zend/apache2/htdocs/project/public/index.php
Error String Uncaught exception 'Zend_Locale_Exception' with message 'The locale '' is no known locale'
If someone could help it would be much appreciated.
Thanks
SP

How to implement data model with this code

I am new to zend frame work . I am trying to learn zf create db-table tblename,zf create model tblname,zf create model tblnameMapper.
add user.php (form)
<?php
class Application_Form_Adduser extends Zend_Form
{
public function init()
{
$this->setMethod('post');
$username = $this->createElement('text','username');
$username->setLabel('Username:')
->setAttrib('size',10);
$password=$this->createElement('text','password');
$password->setLabel('Password')
->setAttrib('size',10);
$reg=$this->createElement('submit','submit');
$reg->setLabel('save');
$this->addElements(array(
$username,
$password,
$reg
));
return $this;
}
add user view:
<?php
echo 'Add user';
echo "<br />" .$this->a;
echo $this->form;
?>
admin controller:
<?php
class AdminController extends Zend_Controller_Action
{
public function adduserAction(){
$form = new Application_Form_Auth();
$this->view->form = $form;
$this->view->assign('a','Entere new user:');
if($this->getRequest()->isPost()){
$formData = $this->_request->getPost();
$uname=$formData['username'];
$pass=$formData['password'];
$msg=$uname." added to database successfully";
$this->view->assign('a',$msg);
$db= Zend_Db_Table_Abstract::getDefaultAdapter();
$query="INSERT INTO `user` ( `id` , `uname` , `password` )
VALUES ('', '{$uname}', '{$pass}');";
$db->query($query);
}}
i want to implement db-table with the above code .i am new to zend frame work i spend some time on reading programmers guide but in vain .It is very hard to get things from manual.So please some one explain step by step procedure for implementing the same .Thanks in advanced.
Ok here is a quick example:
Create DbTable Model (Basically an adapter for each table in your database):
at the command line: zf create db-table User user add -m moduleName if you want this in a module. This command will create a file name User.php at /application/models/DbTable that looks like:
class Application_Model_DbTable_User extends Zend_Db_Table_Abstract {
protected $_name = 'user'; //this is the database tablename (Optional, automatically created by Zend_Tool)
protected $_primary = 'id'; //this is the primary key of the table (Optional, but a good idea)
}
now to create a method in your DbTable model that executes the query from your controller, add a method similar to:
public function insertUser(array $data) {
$Idata = array(
'name' => $data['name'] ,
'password' => $data['passowrd']
);
$this->insert($Idata); //returns the primary key of the new row.
}
To use in your controller:
public function adduserAction(){
$form = new Application_Form_Auth(); //prepare form
try{
if($this->getRequest()->isPost()){//if is post
if ($form->isValid($this->getRequest()_>getPost()){ //if form is valid
$data = $form->getValues(); //get filtered and validated form values
$db= new Application_Model_DbTable_User(); //instantiate model
$db->insertUser($data); //save data, fix the data in the model not the controller
//do more stuff if required
}
}
$this->view->form = $form; //if not post view form
$this->view->assign('a','Entere new user:');
} catch(Zend_Exception $e) { //catach and handle exception
$this->_helper->flashMessenger->addMessage($e->getMessage());//send exception to flash messenger
$this->_redirect($this->getRequest()->getRequestUri()); //redirect to same page
}
}
This is about as simple as it gets. I have barely scratched the surface of what can be accomplished in simple applications with Zend_Db and a DbTable model. However you will likely find as I have, that at some point you will need more. That would be the time to explore the domain model and mappers.
For a really good basic tutrial that includes all of this and more please check out Rob Allen's ZF 1.x tutorial
I hope this helps.

not able to login using zend framework

I am new to zend. I am trying to create login form using zend framework. But its creating problem. Below is my function
public function loginAction()
{
$db = $this->_getParam('db');
$form = new Application_Form_Login();
$this->view->form = $form;
if($this->getRequest()->isPost())
{
$formData = $this->getRequest()->getPost();
if ($form->isValid($formData))
{
$adapter = new Zend_Auth_Adapter_DbTable(
$db,
'users',
'emailaddress',
'password',
'MD5(CONCAT(?, password_salt))'
);
$adapter->setIdentity($form->getValue('email'));
$adapter->setCredential($form->getValue('password'));
$auth = Zend_Auth::getInstance();
$result = $auth->authenticate($adapter);
if ($result->isValid()) {
$this->_helper->FlashMessenger('Successful Login');
$this->_redirect('/');
return;
}
}
}
}
its giving error on following line -> $result = $auth->authenticate($adapter);
Error is -> Message: The supplied parameters to Zend_Auth_Adapter_DbTable failed to produce a valid sql statement, please check table and column names for validity.
my table name is 'users' and it has columns(id,firstname,lastname,age,emailaddress,password).
You need field named 'password_salt' in your table which will contain salt or just change this
'MD5(CONCAT(?, password_salt))'
to
'MD5(?)'