I want to access the currently logged in user in my Helper function using AJAX.
function editUser(){
runAjax('editUser',"one");
}
function runAjax(type,regHtml){
request = {
'option' : 'com_ajax',
'module' : 'user_login',
'cmd' : type,
'params' : params,
'format' : 'json'
};
jQuery.ajax({
type : 'POST',
data : request,
success: function (response) {
The editUser function is set off via a onmousedown button.
This all works fine and calls the helper function. The issue is on the helper side.
public static function getAjax()
{
function setUpForm(){
$user = JFactory::getUser();
echo "<pre>";
print_r($user);
echo "</pre>";
}
$input = JFactory::getApplication()->input;
$params = $input->get('params',"",raw);
$cmd = $input->get('cmd');
if($cmd == "editUser"){
setUpForm();
}
This works but isn't the recommended way of getting the user object. It's:
use Joomla\CMS\Factory;
$user = Factory::getUser();
This is the switch to use cases but this won't work with AJAX because the use won't work out of context I'd need to do something like:
define('JPATH_BASE', realpath(dirname(__FILE__) . '/../..'));
require_once JPATH_BASE . '/includes/defines.php';
require_once JPATH_BASE . '/includes/framework.php';
to include extra files (I haven't tried it since it seems a mad way to go)
Is there a way around this.
Whilst I have working code I'm thinking about future proofing my code.
Update
I'm adding some cleaner code to show what doesn't work:
This doesn't work because it doesn't have the namespace context
class modLoginHelper
{
public static function getAjax()
{
use Joomla\CMS\Factory as YourNewAlias;
user = Factory::getUser();
}
}
This won't throw an error but doesn't work
class modLoginHelper
{
use Joomla\CMS\Factory as YourNewAlias;
public static function getAjax()
{
user = Factory::getUser();
}
}
So whichever way I try to follow the use Joomla ... it won't work - I have to revert to the old way of doing things.
JFactory::getUser()
vsJoomla\CMS\Factory::getUser()
?JFactory
is just an aliased namespace forJoomla\CMS\Factory
- see the classmap - github.com/joomla/joomla-cms/blob/staging/libraries/… - are you getting the old "Cannot use Joomla\CMS\Factory as Factory because the name is already in use" error? If so, alias that, so something likeuse \Joomla\CMS\Factory as YourNewAlias
and thenYourNewAlias::getUser()
.setUpForm()
, especially since you already have a class.