Get user object inside an entity - php

I'm trying to get user object inside an entity. I'm using FosUserBundle and PugxMultiUserBundle, and I tried the following command:
container->get('fos_user.user_manager')->getToken()->getUser();
but I get:
Undefined property $container
How can I fix it?
Thank you for your help.
The function that doesn't work is inside an entity, and it is the following:
protected function getUploadDir()
{
$userManager = $this->container->get('security.context');
$user = $userManager->findUserByUsername($this->container->get('security.context')
->getToken()
->getUser());
return 'uploads/'.$user;
}

UPDATE after #OP edited...
You cannot access the container (hence the userManager) from an entity. The entity should not access the container itself.
You are missing $ before the name of your variable.
But that's not all, solution inside a controller :
$userManager = $this->container->get('fos_user.user_manager');
$user = $userManager->findUserByUsername($this->container->get('security.context')
->getToken()
->getUser())
But, inside a controller, your should be able to get user by doing the following :
$this->getUser();

Related

get loggedIn user in View Composer not working(Sentinel - Laravel 5.4)

I am using Sentinel in Laravel 5.4. What I am trying to do is: get logged user detail but Sentinel::getUser() returns null. For this process, I have seen this instruction in this answer
. I am following using View Composer method.
Steps I have done
I have created a file ViewComposerServiceProvider inside Providers folder. It looks like:
public function boot()
{
$user = Sentinel::getUser(); //<<-- main error: dd($user) returns empty
$userDetail = UsersDetail::where('user_id', $user->id)->firstOrFail();
if ( is_null ($userDetail) ) {
$userDetail = new UsersDetail;
}
view()->composer('backend.*', function($view) {
$view->with('userDetail', $userDetail);
//$view->with('userDetail', 'Test'); //this works fine
});
}
Then, I register this provider in config/app.php Providers array as
App\Providers\ViewComposerServiceProvider::class,
When, I pass other variables in userDetail, it's working perfectly. But, I cannot get the logged in user detail. Am I missing something?
Following the first solution from this answer also seems not working since, construct are run prior to the Middleware. Any help please.
Go to app\Providers\AppServiceProvider.php
Then your serviceProvider.php boot method like below
public function boot()
{
$user = Sentinel::getUser(); //<<-- main error: dd($user) returns empty
$userDetail = UsersDetail::where('user_id', $user->id)->firstOrFail();
if ( is_null ($userDetail) ) {
$userDetail = new UsersDetail;
}
View::composer('userDetail', function($view) use($userDetail ) {
$view->with('userDetail ',$userDetail );
});
}
Then your userDetail.blade.php you can access userDetail data like this
{{ $userDetail }}

Symfony2 entity manager get not working all the time

I found a strange issue in symfony2 (maybe is not strange and i did a mistake somewhere):
i'm trying to call an entity manager method that i defined in the entity class:
//Entity/organisation.php
/**
* #return string
*/
public function getApiUrl(){
return $this->api_url;
}
and i don't always get a return value for the same object
the call is made from a controller method:
private function addApiLog($organisationId, $callType, $eventInfo){
$em = $this->getEntityManager();
$organisation = $em->find('\WebAgenda\Entity\Organisation', $organisationId);
if (null === $organisation) {
die();
}
$apiUrl = $organisation->getApiUrl();
$apiKey = $organisation->getApiKey();
$fc = fopen("debug_api_log.txt", "a");
fwrite($fc, date("Y-m-d H:i:s")." - ".$callType." - ".$organisationId." - ".$organisation->getName()." - ".$apiUrl."\n");
fclose($fc);
if(trim($apiUrl)!='' && $apiUrl!='-'){
the 'addApiLog()' methos is called from different methods depending on the action and even though the organisationId that is passed to it is the same and i get the organisation object, sometimes the $organisation->getApiUrl() method doesn't return anything and the $organisation->getName(), always return the correct value: http://screencast.com/t/HQ2NuNfWSG9
What am I missing? Why i don't get values?
Thank you!
Replace $em = $this->getEntityManager();
With this $em = $this->getDoctrine()->getManager();
And then use your repository
$myRepo = $em->getRepository('NamespaceMyBundle:Organisation');
$organisation = $myRepo->find($organisationId);
You said the addApiLog() method is called from different methods depending on the action.
Maybe not all your methods have access to the Context ?

How to 3rd party application access to Yii2 (HumHub)

I want to give a 3rd party PHP application access to Yii2 user data (HumHub) and have tried this:
function getUserId() {
require_once('../protected/vendor/yiisoft/yii2/Yii.php');
$yiiConfig = require('../protected/config/common.php');
(new humhub\components\Application($yiiConfig));
$user = Yii::$app->user->identity;
return $user;
}
This does not work. There are no errors up until new humhub\components\Application($yiiConfig) but then the 3rd party app breaks with no error thrown and the function does not return anything.
I did find this solution which does not work.
Is there are reason this does not work or is there an alternate solution to getting Yii2 user data properly?
This is how to do it in HumHub V1.0
require_once('../protected/vendor/yiisoft/yii2/Yii.php');
$config = yii\helpers\ArrayHelper::merge(
require('../protected/humhub/config/common.php'),
require('../protected/humhub/config/web.php'),
(is_readable('../protected/config/dynamic.php')) ? require('../protected/config/dynamic.php') : [],
require('../protected/config/common.php'),
require('../protected/config/web.php')
);
new yii\web\Application($config); // No 'run()' invocation!
Now I can get $user object:
$user = Yii::$app->user->identity;
Indeed an error should be thrown, but, the error settings of your PHP may be overridden or set to not display errors.
You call undefined object Yii::$app->user->identity. The reason, from documentation because you have not initialized the Yii object. So your code should be as follows:
function getUserId() {
require_once('../protected/vendor/yiisoft/yii2/Yii.php');
$yiiConfig = require('../protected/config/common.php');
(new humhub\components\Application($yiiConfig)); // try to comment this line too if it does not work
// Add The Following Line
new yii\web\Application($yiiConfig); // Do NOT call run() here
$user = Yii::$app->user->identity;
return $user;
}

PHP Laravel : Couldn't track device name using antonioribeiro/tracker

I want to track the device name of the user have used for accessing the site. for that I'm using antonioribeiro/tracker But while accessing the device name it's showing
Trying to get property of non-object
Here is the controller I have used for that:
public function postUser(Request $request)
{
$user=new User();
$user->name= $request->Input(['name']);
$user->email=$request->Input(['email']);
$user = Tracker::currentSession();
dd($user->device->platform) ;
//dd( $user->device->is_mobile);
// $pageViews = Tracker::pageViews(60 * 24 * 30);
// dd($pageViews);
$user->save();
return redirect('userPage');
}
How do I resolve my problem. If anyone find the solution please provide a valid one.

Zf2 and Doctrine Annotations give trouble to make a 'new' form

I am trying to create a form to create a new product.
In my Controller I have the follwoing code:
public function newAction() {
$repo = $this->getEntityManager()->getRepository('Swap\Entity\Product');
$builder = new AnnotationBuilder($this->getEntityManager());
$form = $builder->createForm($repo);
$config = $this->getModuleConfig();
if (isset($config['swap_form_extra'])) {
foreach ($config['swap_form_extra'] as $field) {
$form->add($field);
}
}
$form->setHydrator(new DoctrineHydrator($this->getEntityManager(), 'Swap\Entity\Product'));
$form->bind($repo);
return new ViewModel(array('form' => $form));
}
Now this gives me the follwing error:
Class "Swap\EntityRepository\Product" sub class of "Doctrine\ORM\EntityRepository" is not a valid entity or mapped super class.
I am not sure if this has anything to do with it: But when you want to edit an object in a form you can do:
$repo = $this->getEntityManager()->getRepository('Swap\Entity\Product');
$id = (int) $this->getEvent()->getRouteMatch()->getParam('id', '0');
$product = $repo->find(1);
$productNames = $this->getEntityManager()->getRepository('Swap\Entity\ProductGroup')->findAll();
$product->SetProductGroup($productNames);
$builder = new AnnotationBuilder($this->getEntityManager());
$form = $builder->createForm($product);
But not sure how to get the product in a form to create a new entity.
Any suggestions?
Forms are build around entities, not with repositories. There is a clear distinction between them in Doctrine: entities are objects that hold state, that are related to database tables and where you can create new ones, update existing ones and remove ones for. Repositories are helper classes. They help you to find entities. Usually you find one by id or find them all, but repositories help you also to find one or multiple entities via a specific property.
That said, the form builder requires entities. In both the edit as the new action, you want to build based on the entity. In the editAction, you do this (pseudo):
$product = findMyProductEntity();
$form = $builder->createForm($product);
In the newAction, you do this (pseudo):
$repository = findMyProductRepository();
$form = $builder->buildForm($repository);
In this case, you also need to inject the entity and not the repository. How? Simply, just use new:
public function newAction()
{
$product = new Swap\Entity\Product;
$builder = new AnnotationBuilder($this->getEntityManager());
$form = $builder->createForm($product);
// Rest of your code
}
You told it to build the form from an entity repository instance, and not an entity itself.
$form = $builder->createForm($repo); // $repo is not an entity!

Categories