I'm writing a Joomla 2.5 component that I had been developing in Joomla 1.7. I have been using code like this:
$user = JFactory::getUser();
$groups = $user->get('groups');
The $groups array would contain a list of ids with the group name as the index. Joomla 2.5 seems to have scrapped this functionality. I have been unable to find out how to get the group names without directly querying the database. Is there any method for getting a list of the groups a user is a member of without having to resort to querying the database?
The code I generated below gets the names of all the groups the user is a part of and stores them in the variable $groupNames separated by line breaks:
foreach ($user->groups as $groupId => $value){
$db = JFactory::getDbo();
$db->setQuery(
'SELECT `title`' .
' FROM `#__usergroups`' .
' WHERE `id` = '. (int) $groupId
);
$groupNames .= $db->loadResult();
$groupNames .= '<br/>';
}
print $groupNames;
It technically queries the database but is done via the Joomla API. This is working well for me on Joomla 2.5.
Yes, this changed.
But what you should be using instead is:
JFactory::getUser()->getAuthorisedGroups();
or just getUserGroups
Real snippet:
$user = JFactory::getUser();
$db = JFactory::getDBO();
$db->setQuery($db->getQuery(true)
->select('*')
->from("#__usergroups")
);
$groups=$db->loadRowList();
$userGroups = $user->groups;
$return=array();
foreach ($groups as $key=>$g){
if (array_key_exists($g[0],$userGroups)) array_push($return,$g[4]);
}
$groups=$return;
/////printing groupnames for current user/////////////
print_r($groups);
Here it is:
<?php
$user =& JFactory::getUser();
foreach ($user->groups as $key => $value){
echo $key.'<br>';
}
?>
This will print all the user group names to the screen. The user group names are the "keys" of the array $user->groups.
Related
Im trying to find a session by PART of its ID in laravel.
I only have the first part of the id, and I need to find if the session has a key/value associated with it.
I have tried various forms of the below code. Its fairly simple but not sure if possible in laravel.
Note
Im not sure if this helps or not, but the laravel system is using file based sessions, not DB based sessions.
$value = 'do i have this value';
// Session::all()->whereLike('id','aVhN8u' . '%')->get();
foreach( Session::all()->where('id')->startsWith('aVhN8u') as $session)
{
if($session->has('key', $value)
{
// Do something interesting
}
}
Something like this should work.
use Illuminate\Support\Str;
$value = 'my cool value';
$prefix = 'aVhN8u';
$stored = session()->all();
$filtered = collect($stored)->filter(function ($session, $key) use ($prefix, $value) {
return Str::startsWith($key, $prefix) && $session == $value;
})->all();
How to use Prepare methods in joomla model?
for example in pdo we use :
db->prepare('INSERT INTO tbl (`city`,`date`,`uid`,`title`) VALUES(:city,:date,:uid,:title)');
How can I do it in the Joomla!
In Joomla, you always stick to the API which caters for the supported database types, like so:
$db = JFactory::getDbo();
$query = $db->getQuery(true);
$columns = array('city', 'date', 'uid', 'title');
$values = array($db->quote('value1'), $db->quote('value2'), $db->quote('value3'), $db->quote('value4'));
// Prepare the insert query.
$query
->insert($db->quoteName('#__tablename')) //make sure you keep #__
->columns($db->quoteName($columns))
->values(implode(',', $values));
$db->setQuery($query);
$db->query();
and for Joomla 3.x, you can replace $db->query(); with $db->execute();
Update:
As far as I know, Joomla 4 will use prepared statements in core. Here is a something I've mocked up, however have not tested:
use Joomla\CMS\Factory;
use Joomla\Database\ParameterType;
$db = Factory::getDbo();
// Your data
$city = $db->quote('London');
$date = $db->quote('21/01/2020');
$uid = $db->quote(1234);
$title = $db->quote('My Title');
// Prepared query
$query = $db->getQuery(true)
->insert($db->quoteName('#__tablename'))
->columns([
$db->quoteName('city'),
$db->quoteName('date'),
$db->quoteName('uid'),
$db->quoteName('title'),
])
->values(':city, :date, :uid, :title')
->bind(':city', $city, ParameterType::STRING)
->bind(':date', $date)
->bind(':uid', $uid, ParameterType::INTEGER)
->bind(':title', $title, ParameterType::STRING);
$db->setQuery($query);
$db->execute();
I would like to display all login user list in Front side using Joomla 2.5 component.
Can any body tell me how do do this?
I would also want to develop change password and news subscription module.
Try this,
$db =JFactory::getDBO();
$query = $db->getQuery(true);
$query->select('*')
->from('#__users');
$db->setQuery($query);
$rows = $db->loadObjectList();
foreach ($rows as $row) {
$user = JFactory::getUser($row->id);
$status = $user->guest;
if(!$status){
echo $row->name.'---Email'.$row->email;
}
}
Use this extension to implement its in your site if you need quick solution.
Hope it helps..
Im trying to load data from extra_fields field from k2_items table inside external php script (let's call it locations.php) which I would like to include somewhere else on the site.
Data in extra_field field is json encoded:
[{"id":"1","value":"somevalue"},{"id":"2","value":"somevalue"},{"id":"3","value":"somevalue"}.]
For example: I have items with ids 1,6,10,15,22,44 and 66.
I would like to have variables for each extra field and for each item so I can use them elsewhere.
If item with id 1 has 3 extra fields, I would like to have variables $item1ExtraField1, $item1ExtraField2 and $item1ExtraField3.
So first I initiated Joomla framework:
// Get Joomla Framework
defined('_JEXEC') or die('Restricted access');
define( 'JPATH_BASE', realpath(dirname(__FILE__)));
define( 'DS', DIRECTORY_SEPARATOR );
require_once (JPATH_BASE.DS.'includes'.DS.'defines.php' );
require_once (JPATH_BASE.DS.'includes'.DS.'framework.php' );
require_once (JPATH_BASE.DS.'libraries'.DS.'joomla'.DS.'factory.php' );
$mainframe =& JFactory::getApplication('site');
$mainframe->initialise();
Then I tried DB query with 2 ids to see if I can get data:
// Load the data from the database.
$db = JFactory::getDbo();
$query = $db->getQuery(true);
$query
->select('extra_fields')
->from('#__k2_items')
->where('id = 15 or id= 289');
$db->setQuery($query);
$items = $db->loadObjectList();
// Check for a database error.
if ($db->getErrorNum())
{
$this->_subject->setError($db->getErrorMsg());
return false;
}
Then I get slowly lost.
I get no results if I try:
foreach ($items as $item) {
echo json_decode($item);
}
and var_dump gives me
array(2) { [0]=> object(stdClass)#1395 (1) { ["extra_fields"]=> string(1013) "[{"id":"3","value":"somevalue"},{"id":"4","value":"somevalue"}, etc ]
or using jdump extension:
[array] (unknown name)
[stdClass object] 0
Properties
[string] extra_fields = "[{"id":"3","value":"somevalue"},{"id":"4","value":"somevalue"}, etc ]"
[stdClass object] 1
Properties
[string] extra_fields = "[{"id":"3","value":"somevalue"},{"id":"4","value":"somevalue"}, etc ]"
So Joomla framework initialization seems ok, DB connection is there, but I'm not sure how to continue.
Any help would be appreciated.
I see the problem is with decoding json string. Try something like this:
$query = mysql_query($sql,$con);
while ($item = mysql_fetch_array($query))
{
$fields =(array)json_decode($item['extra_fields']);
$field1 = $fields[0]->value;
$field2 = $fields[1]->value;
}
I am new to Joomla. I have created website using Joomla 2.5. I have login page which is default Joomla user management system.
What I want is display all user data in a tabular format. How could I do the same?
Edit 1
I can see the users with below steps.
Go to administrator page as www.site.com/administrator.
Login as admin
Click Users >> User Manager menu and then I can see the list of users.
I want to print same list, however on the website and not on administrator site at backend.
you can do this run the query on your page where you want to show user list. you can fetch all users table field with $row object.
$db =& JFactory::getDBO();
$query = "SELECT * FROM #__users" ;
$db->setQuery($query);
$rows = $db->loadObjectList();
foreach ($rows as $row) {
echo $row->id.'|'.$row->username.'|'.$row->email;
}
Edit 1
Below is what I used.
Installed extension Flexi Custom Code.
Create module using this, add above code in it and appear that menu on the menu where you want to display.
You'll need some sort of component for this. This user profile component for example (N.B. Using this as my example as a work colleague once used it - not as customizable as I would have liked - but probably OK for what your after. I'm sure there are more as there's an entire member list category.)
Just install one of them and choose what you want to show. Add it to a menu like any other component and off you go!
Two possible solutions
Use the User Profile Component available in JED
Enable "User - Contact Creator" plugin to create a Contact profile for each new user and then use the Joomla built-in Menu Item to list all contacts
// my example with opt-groups, preselected user and better user-ids
function getUserList ($user_id) {
$db = JFactory::getDBO ();
$db->setQuery ("SELECT id, username, usertype FROM ' . $db->quoteName ('#__users') . ' ORDER BY usertype,username ASC");
$rows = $db->loadAssocList ();
static $opt_tag;
$list = '<option value="0">' . JText::_ ('SELECTION') . '</option>';
foreach ($rows as $row) {
if (empty ($opt_tag) || $opt_tag != $row['usertype']) {
$list .= '<optgroup label="' . $row['usertype'] . '">';
$opt_tag = $row['usertype'];
}
if ($row['id'] < 10) {
$id = '000' . $row['id'];
}
elseif ($row['id'] < 100) {
$id = '00' . $row['id'];
}
elseif ($row['id'] < 1000) {
$id = '0' . $row['id'];
}
$list .= '<option value="' . $row['id'] . '"' . (((int) $user_id == $row['id']) ? ' selected="SELECTED"' : '') . '>' . $id . ' - ' . $row['username'] . '</option>';
if (empty ($opt_tag) || $opt_tag != $row['usertype']) {
$list .= '</optgroup>';
}
}
return $list;
}