-1

On my site I want to set cron job that will check if user already submited form that allow them to browse website freely. I tried to catch user id (and assign a new role id) in \core\lib\Drupal\Core\Cron.php using

$user = \Drupal\user\Entity\User::load(\Drupal::currentUser()->id());
      error_log($user->get('uid')->value);

but it seems like it doesn't know context of user and prints just 0. Is there anyway to do this? Is this even possible in drupal?

2 Answers 2

0

In order to load the user, your are passing the UID of the current user, is it not what you want ?

\Drupal::currentUser()->id()

I don't have a full vision of what you want, but it should return the current user UID.

4
  • It returns 0 every time
    – karoluS
    Jul 5, 2017 at 9:45
  • Because cron is run as the anonymous user (id=0)
    – Clive
    Jul 5, 2017 at 12:21
  • Are you implementing hook_cron() or something else ? You are not trying to directly edit the Cron.php from core ? Other guess, if you are not connected, you are an anonymous user and UID is always 0
    – guilhom
    Jul 5, 2017 at 12:26
  • i was editing Cron.php
    – karoluS
    Jul 6, 2017 at 18:38
0

Ok I managed to do it by using

$user = user_load_by_name('user');
$user->addRole('administrator');
$user->save();

that way i got user and i could assign it a designated role.

Unfortunatelly I can't show you webservices handling code due to company policy.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.