Initialize a field in all users profile


Sometimes you create a new field on the user account when you already have users created. New users will get the default value of the field but old users won't.

This snippet initializes a boolean field called receiveemail to 1 for all the users on the site.

If unsure about the name of the field, uncomment the line starting with dpm to see what's available to the wrapper.

This code uses Entity API and devel's DPM function.

</> CopyGet raw version
  1. $users = entity_load('user');
  3. foreach ($users as $user) {
  4. $wrapper = entity_metadata_wrapper('user', $user);
  5. if ($wrapper->uid->value() != 0) {
  6. //dpm($wrapper->getPropertyInfo());
  7. $wrapper->field_receiveemail = 1;
  8. $wrapper->save();
  9. }
  10. }