Score:0

Programmatically saving data in a field under user account

cn flag

QR codes have been printed out for a bunch of students in a university. When they visit the site via those QR codes, and they are logged-in, the refcode query parameter used in the link needs to be saved for their account in a field_usr_ref_code field (a Text (plain) field).

In a .module file I am using the following code.

use Drupal\user\Entity\User;

/**
 * Implements hook_entity_load().
 */
function my_custom_module_entity_load() {
  $refcode = \Drupal::request()->query->get('refcode');
  $user_id = \Drupal::currentUser()->id();
  if ($user_id > '0' && isset($refcode)) {
    $account = User::load($user_id);    
    $account->set('field_usr_ref_code', $refcode);
    $account->save();
  }
}

However, for some reason no data is being saved, without any logged error.

What is wrong with the code I am using?

No Sssweat avatar
ua flag
Quotes are for strings, not for numbers/integers. `$currentuserid > '0'` is best to have as `$currentuserid > 0`. In addition, `else { // Do nothing }` if you are really doing nothing, then delete the else code, as having an else is not mandatory for if statements.
No Sssweat avatar
ua flag
However, despite having those 2 blemishes that I pointed out in my previous comment, your code should've worked. So your issue is else where. In the hook function name, did you rename the `my_custom_module` part to your actual custom module's name? Did you make sure your module is indeed enabled? You could also add `\Drupal::logger('my_custom_module')->notice('My HOOK works!');` in your hook code to check that your hook is needed being executed. Then go to `/admin/reports/dblog` and check if it got logged.
id flag
Drupal 8 is end of life. Each day the risk increases that the site will be hacked.
Maher B avatar
cn flag
@NoSssweat I have updated my code based on your input; And yes the module is enabled, all caches are cleared and the module is renamed as it should be... Still not working
id flag
Is the module’s meta file named my_custom_module.info.yml?
Maher B avatar
cn flag
Yes, the module is already working and contains another function which is: `function my_custom_module_form_alter(&$form, FormStateInterface $form_state, $form_id) {}`
apaderno avatar
us flag
`hook_entity_load()` is the wrong hook to use for code that should be executed when a page is visited.
id flag
Truly, and it has the wrong signature.
Maher B avatar
cn flag
@apaderno can you suggest what function should be use instead ?
Score:0
cn flag

Use a request event subscriber with a priority of 299:

/src/EventSubscriber/MymoduleSubscriber.php

<?php

namespace Drupal\mymodule\EventSubscriber;

use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\HttpKernel\Event\RequestEvent;

/**
 * Mymodule event subscriber.
 */
class MymoduleSubscriber implements EventSubscriberInterface {

  /**
   * Kernel request event handler.
   *
   * @param \Symfony\Component\HttpKernel\Event\RequestEvent $event
   *   The request event.
   */
  public function onKernelRequest(RequestEvent $event) {
    if (!$event->isMainRequest()) {
      return;
    }
    // put here your code
  }

  /**
   * {@inheritdoc}
   */
  public static function getSubscribedEvents() {
    return [
      KernelEvents::REQUEST => ['onKernelRequest', 299],
    ];
  }
}
   

mymodule.services.yml

services:
  mymodule.event_subscriber:
    class: Drupal\mymodule\EventSubscriber\MymoduleSubscriber
    tags:
      - { name: event_subscriber }

Drupal runs authentication with priority 300.

This code is for Drupal 9/10.

For Drupal 8 you need to use Symfony\Component\HttpKernel\Event\GetResponseEvent and $event->isMasterRequest().

id flag
For Drupal 8 you need to use Drupal 9
I sit in a Tesla and translated this thread with Ai:

mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.