Joomla 3 get profile - joomla

I use function onUserAfterSave and $isnew, but I can't get phone and address of user registered in Joomla 3.X. I only can get name, username, email, but no data from profile.

To access the user profile data you need to use JUserHelper class
jimport( 'joomla.user.helper' );
$user = JFactory::getUser();
$userProfile = JUserHelper::getProfile( $user->id ); //Get userprofile data
//You can get all the user input of profile data. If you want to get country of user use
echo "Country :" . $userProfile->profile['country'];

Amit Ray,
I use in my plugin:
public function onUserAfterSave($user, $isnew, $success, $msg)
{
//die(print_r($user));
if ($isnew){
.............
$pluginParams = new JRegistry($plugin->params);
$name = $user['name'];
$name_usuario = $user['username'];
$email_user = $user['email'];
$id_usuario = $user['id'];
jimport( 'joomla.user.helper' );
$user = JFactory::getUser();
$userProfile = JUserHelper::getProfile( $id_usuario );
//You can get all the user input of profile data. If you want to get country of user use
$user_phone = $userProfile->profile['phone'];
$user_address = $userProfile->profile['address1'];
But $user_phone and $user_address no have data... whats is error? Thanks

Related

How can I save iframe content in Laravel?

I have a settings page in my admin panel where the user can paste their Google map iframe code (embed code). The setting options are saved in the database and displayed in various places on the front-end.
My problem is that when I save the settings, the map embed code isn't saved to the database. I guess it's a sanitization problem.
Here is my code from my controller:
public function updateGeneral(Request $request) {
$id = $request->id;
$data = array();
$data['site_title'] = $request->site_title;
$data['meta_description'] = $request->meta_description;
$data['site_lang'] = $request->site_lang;
$data['company_name'] = $request->company_name;
$data['address'] = $request->address;
$data['phone'] = $request->phone;
$data['map'] = $request->map;
$data['email'] = $request->email;
$data['facebook'] = $request->facebook;
$data['twitter'] = $request->twitter;
$data['youtube'] = $request->youtube;
$data['insta'] = $request->insta;
// Update table with new data
DB::table('settings')->where('id', $id)->update($data);
return redirect(route('admin.settings'))->with('successMsg', 'Settings have been updated successfully!');
}
So how can I make sure that the data is saved for:
$data['map'] = $request->map;
Sorry, just realized there was a typoo in form name field. But I also had to change the db field from varchar to text.

How can I pass username in controller?

Username is store in my session. I am working on leave management module.
My Leave module's table has these fields
User Name, Leave Type, Duration, Status, & Action.
Apart from username all details I can insert and list in list view.
But my user name is store in session.
How can i get it from session and store in database In Username field??
Code in my view file
#if(Session::has('key'))
<?php $username = Session::get('key')['username']; ?>
#endif
<input type="hidden" name="username" value="<?php echo $username ?>">
Code In My controller file
public function leaveApplication(Request $request)
{
$leave = new LeaveManagement();
$leave->username = $request->get('username');
$leave->leaveType = $request->get('leaveType');
$leave->startDate = $request->get('startDate');
$leave->endDate = $request->get('endDate');
$leave->fromLeave = $request->get('fromLeave');
$leave->fromHalfDayLeaveType = $request->get('fromHalfDayLeaveType');
$leave->toLeave = $request->get('toLeave');
$leave->toHalfDayLeaveType = $request->get('toHalfDayLeaveType');
$leave->fullDayLeave = $request->get('fullDayLeave');
$leave->typeOfLeave = $request->get('typeOfLeave');
$leave->reasonForLeave =$request->get('reasonForLeave');
$leave->status = 'Pending';
$leave->save();
return redirect('leave');
}
You can use Laravel global session helper: session(keyName).
To get username from session and store it in database:
$username = session('username');
$leave = new Leave();
$leave->username = $username;
$leave->save();
For more information on Laravel session see Laravel Session
you can get object from your session and access to its attributes.some thing like:
$user = session()->get('user')
$username = $user->username
or after logging you can access your user's username with:
auth()->user()->username
After login, Auth maintains user table fields in it. You can access it like that -
echo Auth::user()->name or echo Auth::user()->email
It will return the expected values as : "usersname" and "useremail#domain.com".
If you are not using Auth, then you can get username from your session and save it in DB like that -
$user = session()->get('user')
$username = $user->username;
$leave = new LeaveManagement();
$leave->username = $username;
$leave->save();
Hope this will help you.

Can't filter data from database using getSelect()->where() Magento 2

I am currently working with magento 2.2.1 and I am having a weird problem. I am trying to get a set of data from database and display it on admin grid. I want to take records for a specific agent ID so i have a variable that has the value of the agent id. When i pass this variable as parameter to$this->collection->getSelect()->where('agent_id = ?', $this->givenAgentId); it wont display anything but if i replace $this->givenAgentId with it's value, for example with 4, it works perfectly!
This is my class:
<?php
namespace vendor\plugin\Ui\Component\Listing\DataProviders\Atisstats\Coupons;
use \vendor\plugin\Model\ResourceModel\Coupons\CollectionFactory;
use \Magento\Framework\Registry;
class Listing extends \Magento\Ui\DataProvider\AbstractDataProvider {
protected $_registry;
protected $givenAgentId = 0;
public function __construct(
Registry $registry,
$name,
$primaryFieldName,
$requestFieldName,
CollectionFactory $collectionFactory,
array $meta = [],
array $data = []
) {
parent::__construct($name, $primaryFieldName, $requestFieldName, $meta, $data);
$this->_registry = $registry;
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$resource = $objectManager->get('\Magento\Framework\App\ResourceConnection');
$connection = $resource->getConnection();
$select = $connection->select()
->from(
['amasty_perm_dealer'],
['user_id']
);
$data = $connection->fetchAll($select);
foreach ($data as $dealerId) {
if ($dealerId['user_id'] == $this->_registry->registry('admin_session_id')) {
$this->givenAgentId = intval($this->_registry->registry('admin_session_id'));
}
}
if ($this->givenAgentId != 0) {
$this->collection->getSelect()->where('agent_id = ?', $this->givenAgentId);
} else {
$this->collection = $collectionFactory->create();
}
}
}
I have stuck here for hours!
I fixed this problem! First of all it was Registry class causing the problem so I used
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$resourceUserId = $objectManager->get('\Magento\Backend\Model\Auth\Session');
to get the user id from session and used it below to check the user! For some reason the registry object was modifying the variable holding the current users id!
I post the answer just in case someone get stuck with this kind of problem !

How to update existing record using codeIgniter

I have a table like this: id, image, user_id.
The user_id is saved from the session. The same user wants to update his profile picture means, how it will update?
This Is Controller Function
public function save() {
$session_data = $this->session->userdata('logged_in');
$uid= $session_data['id'];
//print_r($uid);exit;
$url = $this->do_upload();
$this->load->model('user_model');
$this->user_model->save($url,$uid);
echo '<script>alert("You Have Successfully Uploaded your Profile Picture!");</script>';
redirect('/home/');
}
This Is Model
public function save($url, $uid){
$this->db->set('image', $url);
$this->db->set('user_id', $uid);
$this->db->insert('tbl');
return true;
}
How can I update this query?
You can do something like the following:
$upd_data = array(
'image' = $url,
);
$this->db->where('user_id', $uid)
->update('tbl', $upd_data);

Add user to group in Joomla not working

I am trying to add a user to a group. I can run this PHP code without any errors, but the user group is still not changed.
<?php
define('_JEXEC', 1);
define('JPATH_BASE', realpath(dirname(__FILE__)));
require_once ( JPATH_BASE .'/includes/defines.php' );
require_once ( JPATH_BASE .'/includes/framework.php' );
require_once ( JPATH_BASE .'/libraries/joomla/factory.php' );
$userId = 358;
$groupId = 11;
echo JUserHelper::addUserToGroup($userId, $groupId);
?>
I run in the same issue with payment callback. I found that user groups save in the database correctly, but are not refreshed in Juser object (becouse You add user to group in different session). When user interacts on a page groups are restored.
Another think that i found is that changing groups in administrator panel works the same way if user is logged in.
To deal with it I made system plugin and in onAfterInitialise function i do:
//get user
$me = JFactory::getUser();
//check if user is logged in
if($me->id){
//get groups
$groups = JUserHelper::getUserGroups($me->id);
//check if current user object has right groups
if($me->groups != $groups){
//if not update groups and clear session access levels
$me->groups = $groups;
$me->set('_authLevels', null);
}
}
Hope it will help.
Possible "Easy" Solution:
The code is correct and it should put your $userId and $groupId in the db to be precise in #__user_usergroup_map .
Btw consider that this method is rising an error if you use a wrong groupId but it's not raising any error if you insert a wrong $userId and for wrong I mean that it doesn't exist.
So there are canches that the user with $userId = 358; doesn't exist.
Update - Hard Debugging:
Ok in this case I suggest you to digg in the code of the helper.
The file is :
libraries/joomla/user/helper.php
On line 33 You have JUserHelper::addUserToGroup.
This is the code:
public static function addUserToGroup($userId, $groupId)
{
// Get the user object.
$user = new JUser((int) $userId);
// Add the user to the group if necessary.
if (!in_array($groupId, $user->groups))
{
// Get the title of the group.
$db = JFactory::getDbo();
$query = $db->getQuery(true)
->select($db->quoteName('title'))
->from($db->quoteName('#__usergroups'))
->where($db->quoteName('id') . ' = ' . (int) $groupId);
$db->setQuery($query);
$title = $db->loadResult();
// If the group does not exist, return an exception.
if (!$title)
{
throw new RuntimeException('Access Usergroup Invalid');
}
// Add the group data to the user object.
$user->groups[$title] = $groupId;
// Store the user object.
$user->save();
}
if (session_id())
{
// Set the group data for any preloaded user objects.
$temp = JFactory::getUser((int) $userId);
$temp->groups = $user->groups;
// Set the group data for the user object in the session.
$temp = JFactory::getUser();
if ($temp->id == $userId)
{
$temp->groups = $user->groups;
}
}
return true;
}
The bit that save the group is $user->save();.
Try to var_dump() till there and see where is the issue.
Author already halfish solved this problem so this answer may help to others. It took me hours of debugging with Eclipse and XDebug to find the issue. This error was very tricky because addUserToGroup() was returning true for me and user object was as well with successful changes, but they were not saved in database. The problem was that onUserBeforeSave() method in my plugin was throwing exception whenever addUserToGroup() was trying to save a user. So check your implementation of onUserBeforeSave() if you touched it. If not you must install Eclipse with XDebug and try to debug what is your exact problem.

Resources