JFactory::getUser($id) not working - joomla

I'm trying to use JFactory::getUser() to get the name and username of a certain user but it returns error!
For example when I write this:
echo JFactory::getUser(645)->name;
it returns this error:
( ! ) SCREAM: Error suppression ignored for
( ! ) Fatal error: Call to a member function load() on a non-object in D:\wamp\www\libraries\joomla\user\user.php on line 888
but it works fine when I enter my own id there, and returns my name!
More info:
I use this function in a field type file, and I already used that in another field type file in the same site and in the same way without any problem! The difference between these is that: I'm using this in a custom component, but that was used in the com_categories component.

pcrikos is right you have to create an instance of the User object first. Once you have done that you call can then object property in an echo statement. Also note that passing no integer (numerical value) to the method will leverage the current user session as the user state and that user id will be used.
//This will instance the user object of the current user state
$user = JFactory::getUser();
//This will instance the user object for a given user defined by passed id aregument
$user = JFactory::getUser(1);
Once you have that object instanced you can call any of the method properties to get the data you seek.
echo $user->name;
echo $user->username;
echo $user->email;
Also note that if you are seeking to get the users ACL's it actually returns as an array. You can see the full object properties and examples here: http://docs.joomla.org/Accessing_the_current_user_object

I thing you should first instantiate a user object.
$user = JFactory::getUser(646);
and then if it is not null (i.e. he/she exists)
do an
echo $user->name;

Related

How to get db field from class object

I execute this update statement which works fine.
$g = Group::where([['id', $idgroup], ['admin', $currentUser]]);
$g->update(['admin' => $iduser]);
After this statement I need the field name from my Group object. But with the following statement I get Undefined property: Illuminate\Database\Eloquent\Builder::$name.
$groupname = $g->name;
Group is my model (DB table) which contains the field id, name, admin. How can I get the field name from this object?
Thank you
Without finder it will return you a query builder but when you need to fetch model instance then apply get (for Collection of model) or first(for single model instance) on query builder. For your case you need to call first() method like this
$g = Group::where([['id', $idgroup], ['admin', $currentUser]])->first();
$g->update(['admin' => $iduser]);
Then you can do
$groupname = $g->name;
You can check the details here for retrieving model
If you want to get one record from database then use first():
$g = Group::where([['id', $idgroup], ['admin', $currentUser]])->first();
$g->name; //it will output name
OR
If you want to get all record from database then use get():
$groups = Group::where([['id', $idgroup], ['admin', $currentUser]])->get();
To get name from here you will have to run loop because get() will return a collection
foreach($groups as $g){
$g->name; //it will give name
}
Your $g variable is a Illuminate\Database\Eloquent\Builder which represent a query, not a single object, which means it doesn't have the Group properties. It's very likely you have more than one record under $g, you have two options retrieve all the names fields like this
$g->pluck('name')
This will give you a collection of all the names, or if you're certain there's one single object, you can do $g->first()->name, it will give you the name of the first object (only one if you're sure there is only one object)

How to get data from variable in ln laravel 5.2

My database table has name, phone, email etc.. fields. Now I store particular field data in different variable and pass them. Here is my code. I tried it from controller function. What should I do?
$var = DB::select("SELECT * FROM reg where email = '$c_email' and Password = '$c_pass' and type = '$c_type'");
$var2 = $var->name;
$var3 = $var->phone;
return redirect('farmer')->with('key', $var2)->with('key2', $var3);
You may try the given way
return view('farmer',compact('var2', 'var3'));
Here 'farmer' is your view page
http://www.easylaravelbook.com/blog/2015/03/09/passing-multiple-variables-into-a-laravel-5-view/
When you're using redirect()->with(), you're flashing data to the session. So to get this data after redirect, use session() helper:
session('key')
https://laravel.com/docs/5.3/responses#redirecting-with-flashed-session-data
use this code. if farmer is view part. or use view part name.
$var=DB::table('reg')
->where('email', $c_email)
->where('password ', $c_pass)
->where('type', $c_pass)
->select('name','phone')
->first();
return view('farmer')->with('var', $var);
get data in view part,
$name=$var->name;
$phone=$var->phone;

Is it possible to set user parametr in joomla without session?

The default JUser::setParam() method sets parameters only to the session. Is is possible somehow to store parameters not in the session, that they would be always available? I also found in users table field params, which stores some parameters for current user, but don't know how to add data there...
Have you tried to save the object after adding your param?
$user = JFactory::getUser();
$user->setParam($key, $value);
$user->save;
An easy and comfortable approach would be to use the popular Community Builder Extension which lets you define custom user fields in the administrator backend. It has an API to obtain the CB User Object and to write and read those fields which get stored in the DB as opposed to the session. Simple example without knowing your Joomla/CB version (works with Joomla 2.5 and CB 1.8) and the place (site, admin, external) where this should be executed (assuming your parameter is named customParam and the user id is 42):
cbimport( 'cb.field' );
$mosCbUser = CBUser::getUserDataInstance(42);
// read value
$customParameter = $mosCbUser->customParam;
// write value
$mosCbUser->customParam = 'newnew';
$mosCbUser->store();
/* write value to DB directly with optional boolean third parameter
specifing whether to trigger the user update plugins
like onBeforeUserUpdate or onAfterUserUpdate
*/
$mosCbUser->storeDatabaseValue('cb_adresse', 'new address', false);
be sure to be in CB plugin context, if not already the case, include e.g. like
global $_CB_framework, $_CB_database, $ueConfig;
$app = JFactory::getApplication();
include_once( $app->getCfg( 'absolute_path' ) . '/administrator/components/com_comprofiler/plugin.foundation.php' );

Checking if specific user is online through php session variable

I'm currently trying to display all online users on my webpage using the php session variables. To do this, whenever a user logs in or out, a column in a database gets set to "online" or "offline".. However this doesn't entirely work since the database doesn't get updated when the user closes their browser (and therefor destroys the session).
So is there another way of checking if a certain sessionid is set??
Currently I am setting the session like this:
session_start();
$_SESSION['username']="Example Username";
To check from the current users page if there is a session variable set we can simply use:
if(isset($_SESSION['username']))
{
//username is set
}
But if we need to check if a specific user is online, how do we get for instance an array of all the session variables that have been set? e.g.
//Get all $_SESSION['username'] vars
//loop through array and check for specific $_SESSION
for($i=0; ... )
{
if( $_SESSION['username'][$i] == "User 1" )
{
//do something
}
}
From all that I've read so far, there doesn't seem to be a way to get an array of all sessions on your page..
So is there a better way of doing it, e.g. how do facebook, twitter, etc handle this stuff?
Thanks for your help!
One solution is to store a timestamp in your database in addition to the online/offline flag that records the last time a user accessed any of your website resources. Then you might just consider them offline after 15 minutes or some other constant value.
The other solution is to play with the callbacks here http://php.net/manual/en/function.session-set-save-handler.php where I think you can handle the gc callback and set the offline flag in your database.
If you search on that page for class SessionDB or go here it looks like somebody has implemented some version of this already in a custom class!
you can use a simple update query
for example you have a table users and in that you have a column called status(online/offline)
on your login.php use
<?php
//your user verification code
if(variable that holds your sql query){
$user_status=('UPDATE user SET status= online WHERE email="'your user email selector'")
}
then on the logout do a similar script just change the online value to offline
You could try this:
foreach ($_SESSION as $sessionKey => $sessionValue)
{
if( $sessionKey == 'username' ) && ( $sessionValue == 'User 1' )
{
//do something
}
}

How do I create, write, and read session data in CakePHP?

can anyone give me an example on how to create Sessions and write data to it. I've seen syntax on how to write data to a session using write command. But how to create a session and retrieve the values in it.
In my application, I have two data, form_id and user_id that needs to be used in all the page requests. So how do I save it as a session variable and use it across the application?
EDIT
function register()
{
$userId=$this->User->registerUser($this->data);
$this->Session->write('User.UserId',$userId);
//echo "session".$this->Session->read('User.UserId');
$this->User->data=$this->data;
if (!$this->User->validates())
{
$this->Flash('Please enter valid inputs','/forms' );
return;
}
$this->Flash('User account created','/forms/homepage/'.$userId);
}
How to use the session variable 'User.UserId' instead of $userId in $this->Flash('User account created','/forms/homepage/'.$userId);
And can I use this variable in all my view files,because in all the page requests I also pass the userId?
EDIT 2
I have 2 controllers,user and form. I write the userid to a session variable in the users_controller. I have a view file called homepage.ctp,whose action is in the forms_controller. Now how can I use the session variable defined in the users_controller in the homepage? Sorry if I am asking silly questions. I went through the cakebook,but my doubts weren't cleared. I'm also trying trial and error method of coding,so please help me.
EDIT 3
I have a session variable 'uid' which is the user id in the home page action of a controller.
$this->Session->write('uid',$this->data['Form']['created_by']);
I need the same variable in the design action method of the same controller.
When I give
$uid=$this->Session->read('uid');
echo "uid: ".$uid;
the value is not echoed.
Can't I use the session variable in the same controller?
The bakery is your best friend:
http://book.cakephp.org/view/398/Methods
All your session read/writes belong in the controller:
$this->Session->write('Person.eyeColor', 'Green');
echo $this->Session->read('Person.eyeColor'); // Green
In cake php you can create session like this
$this->request->session()->write('user_id', 10);
and you can read session value like this
echo $this->request->session()->read('user_id');
Super Simple!
You don't have to write any code to create session, they are already built in. Then you just use the read and write sessions as mentioned above. Also see here for more details:
http://book.cakephp.org/2.0/en/core-libraries/components/sessions.html
Used in Controllers
http://book.cakephp.org/2.0/en/core-libraries/helpers/session.html
Used in Views
cakephp 4 example of session usage in controllers, views and cells
$session = $this->request->getSession();
$session->write('abc', 'apple');
echo $session->read('abc');
In this case it would be:
$this->Flash('User account created','/forms/homepage/'.$this->Session->read('User.UserId'));
and your second question is anwered by Jason Miy (http://api.cakephp.org/class/session-helper). You can simply use this in your view:
$userId = $session->read('User.UserId');
Reading the appropriate cookbook pages slowly and carefully usually helps a lot...
I found out the reason why the uid wasn't being echoed(edit 3 part of the question).
It is due to a silly mistake, had a white space after the end tag ?> in the controller. Now it is working fine.
when I have strange session behavior, and this help me.
MODEL:
function clearAllDBCache() {
$db =& ConnectionManager::getDataSource($this->useDbConfig);
$db->_queryCache = array();
}
`
Acess your Helper SessionHelper in lib/Cake/View/Helper/SessionHelper.php and add the method:
public function write($name = null) {
return CakeSession::write($name);
}

Resources