Score:0

How to inspect the form values in hook_user_update()?

kz flag

In Drupal 7, one could have the following hook_user_update() to return TRUE if the 'roles' has been edited:

function example_user_update(&$edit, $account, $category) {
  isset($edit['roles']) ? TRUE : FALSE;
}

In Drupal 10, the signature of the hook has changed, and we no longer have direct access to the paramter $edit (the array of form values submitted by the user). How do one do this in Drupal 9/10?

function example_user_update(EntityInterface $account) {
  // What is the equivalent?
}
cn flag
The equivalent now would probably be to check `$account->roles` against `$account->original->roles`
Free Radical avatar
kz flag
@Clive Thanks. I guess that will be a workaround, if there is no way to inspect the actual form.
cn flag
It's not really a workaround so much as making better use of an improved architecture - update hooks aren't necessarily triggered by a form submission, so always having form data available doesn't make sense. If the update was triggered by a REST call should your logic not also be considered? (rhetorical question, but that's the thinking behind it). If you need to do something with the form data, you can always hook into the form itself
Free Radical avatar
kz flag
@Clive Thanks for explanation. That makes sense.
Score:0
gb flag

You can follow this code:

function drupal_practice_user_update($account) {
 $roles = $account->original->getRoles();
    if ($roles !== $account->getRoles()) {
      \Drupal::messenger()->addMessage(t('Role has 
       updated'));
    }
    else{
       \Drupal::messenger()->addWarning(t('Role has not 
        updated'));   
    }
}

As you can see $account parameter holds the value of the fields in a users profile.

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.