Hot answers tagged

59

For the sake of more robust and descriptive code, you can make use of the handy User::isAnonymous() method, e.g. if (\Drupal::currentUser()->isAnonymous()) { // Anonymous user... }


52

Instead of trying to prevent the user from registering, which is a game for trolls and hackers alike, make the site annoying for him. Make him want to leave, as opposed to making him want to win the trolling game. What I've done in the past, not specific to Drupal, is to let the user register. I then sabotaged his specific account: I sprinkled if ($...


37

Check here. While it's technically possible to remove the login functionality, you shouldn't, because then your administrator could never log onto the site. In order to remove the register functionality, you simply need to browse to admin/user/settings (for Drupal 6) or admin/config/people/accounts (for Drupal 7 and 8) and select the the "...


35

Something like: $current_user = \Drupal::currentUser(); $roles = $current_user->getRoles(); will return an array like: Array ( [0] => authenticated [1] => administrator [2] => some_other_role ) where the array values are role IDs (equivalent to the machine name of the role in Drupal 7). In OO code, use the appropriate mechanism get the ...


32

Knowing the machine name of the role, it is enough to use user_role_load_by_name(). if ($role = user_role_load_by_name('Role Name')) { // The role ID is in $role->rid. } If the Role might not exist... $role = user_role_load_by_name('Role Name'); $role_id = $role ? $role->rid : NULL;


32

\Drupal::currentUser() returns an Drupal\Core\Session\AccountInterface object. That could be a full user (that would be a Drupal\user\UserInterface), but right now, for the default authentication method, it is not. Use this to get the user entity and all the fields: $user = \Drupal\user\Entity\User::load(\Drupal::currentUser()->id()) D7 had exactly the ...


31

access arguments is for the arguments that will be passed to the callback function...you need to use access callback instead: 'access callback' => 'user_is_logged_in' Since user_is_logged_in() doesn't take any arguments, you can safely remove access arguments for your menu item. Your current code works for the admin account only because the default ...


31

Sorry, used wrong property name first time, an answer: use \Drupal\user\Entity\User; $ids = \Drupal::entityQuery('user') ->condition('status', 1) ->condition('roles', 'moderator') ->execute(); $users = User::loadMultiple($ids); dpm($users);


30

I have just found the answer to this question via Drupal.org. You have to use a URI like this: public://user_pictures/default.png in your account settings. Here, public:// stands for your public files location (often sites/default/files/). What comes after that, is the location of your image within public files. If you do this, the default image is ...


30

Email The Abuser's ISP - They Will Put An End To It! You have a log of his account creation times, and the IP addresses used to register, right? You also have a log of all of his harassing comments as well? Send these logs to their ISP. You can find the ISP by doing an IP lookup either directly with ARIN at https://whois.arin.net/ui or another service ...


27

You can execute drush uli, this will generate a one time login link. By default it provides one-time login link for administrator. If you execute drush uli some-username, this will generate one time login link for that user. UPDATE: You can also use drush upwd for updating the password. Use it like this drush upwd --password=<new password> <some-...


26

Drupal 7.15 allows you to bypass the access on the node. See DANGEROUS_ACCESS_CHECK_OPT_OUT query tag added to EntityFieldQuery for more information. A "DANGEROUS_ACCESS_CHECK_OPT_OUT" query tag has been added to EntityFieldQuery to allow bypassing access checks. Previously, queries executed through EntityFieldQuery would always be altered by the node ...


26

Features is pretty handy for stuff like this. However, if you do need to create roles and add permissions programmatically, you don't have to go digging through the database on your own. When you create a new user role with user_role_save(), it will update the object you passed in with the new user role id that was assigned. You can see an example of this ...


26

I couldn't find anything out there already and it sounded like a handy thing to have, so here's a small module providing a block with a change password form: File: change_password.info name = Change Password description = Provides a block containing a form for the current user to change their password. core = 7.x File: change_password.module <?php /**...


25

Using user_save Drupal function you can create new users like so: $new_user = array( 'name' => 'JohnDoe', 'mail' => 'john.doe@email.com', 'pass' => 'password123', 'status' => 1, 'field_custom_first_name' => array(LANGUAGE_NONE => array(array('value' => 'John'))), // This becomes $account->field_custom_first_name[...


23

A way to add user fields by code so you can put this in your module. I have found this: field_create_field with in the comments a way to create a field for your user upon enabling your module: /** * Implementation of hook_enable(). */ function MYMODULE_enable() { // Check if our field is not already created. if (!field_info_field('field_myField')) { ...


23

Something along the lines of... // Get the field info $info = field_info_field('field_some_field'); // Get a reference to the values $values = &$info['settings']['allowed_values']; // Manipulate the values in some way, e.g. $values['new_value'] = 'New Value'; // Save the field field_update_field($info);


22

The function you could use is user_uid_optional_load(); without arguments, it returns the user object for the currently logged-in user. It still uses the global $user, and loads the full object from the database, including the fields associated to users, but it avoids your code accidentally change the content of the global variable $user, as it is not ...


21

You can use the _user_mail_notify() function, along with a user object, to invoke the password reset email: // Load a user (admin in this case). $account = user_load(1); // Invoke the email. It will be queued along with other system mail to be sent during cron _user_mail_notify('password_reset', $account); A one time login URL with a 24 hour expiry is ...


21

I used hook_node_access() and had the same issue: It wasn't firing and driving me nuts. What worked for me was NOT to be logged in as an admin. I went in as a different role and all worked as expected.


21

Example of how to load current user and retrieve field data from user object. <?php // Load the current user. $user = \Drupal\user\Entity\User::load(\Drupal::currentUser()->id()); // retrieve field data from that user $website = $user->get('field_website')->value; $body = $user->get('body')->value; $email = $user->get('mail')->...


20

I'd like to add a code example that is closer to the original question on how to assign permissions to existing roles programmatically. You can look up the roles with their name, retrieve the role ID and then assign permissions as follows (for example in a hook_update implementation): function custommodule_update_7001() { $permissions = array('view my ...


20

This is quite straightforward with user_roles() and array_search(). Below is a function which will return the role ID if there is a role matching the name and FALSE otherwise. function get_role_by_name($name) { $roles = user_roles(); return array_search($name, $roles); } // Sample usage $rid = get_role_by_name('administrator'); One liner would be: $...


20

And here is how to get it out of that object: // Load the current user. $user = \Drupal\user\Entity\User::load(\Drupal::currentUser()->id()); // Get field data from that user. $website = $user->get('field_website')->value; $body = $user->get('body')->value; // Some default getters include. $email = $user->get('mail')->value; $name = $...


19

In Drupal 7 you can fetch all the users using entity_load like following, $users = entity_load('user'); and array_keys($users) will gives you the array of uid's


19

You just need to call user_save() using code similar to the following one. $edit['pass'] = 'New password'; user_save($account, $edit); $account contains the user object for the user account to alter. I get you load it using user_load(), but it could also be the user object for the currently logged in user. In the latter case, Drupal will regenerate the ...


18

I thought this would be quite tough to do, but as it turns out it's fairly easy. You just need to create a custom module that adds a column to the node table on install, implement hook_schema_alter() so Drupal knows about the new column, and add some logic to provide a value before the node is saved. Here's a small module that will do the trick: File: ...


18

The bad news is that having inspected the code, the form alter layer is the only place to really do this; your approach is pretty much spot on. The good news is, Drupal implements all sorts of static caching throughout the page load, which minimises the need to go back into the database. So while altering the content table may appear cumbersome, you're not ...


18

You can use user_load or \Drupal\user\Entity\User::load to do this. Below code will provide the solution public function content() { $account = \Drupal\user\Entity\User::load('uid'); // pass your uid $name = $account->getUsername(); drupal_set_message($name); } $name gives the username of the user.


Only top voted, non community-wiki answers of a minimum length are eligible