How to recreate the user_picture field?
-
17-01-2021 - |
Question
On Drupal 8 there is by default a user_picture field for the user's photo. When I started my site several months ago, I deleted this field because I did not use it.
Today I need this field, so I created an image type field.
MY PROBLEM : I installed some modules that use the user's photo, but it can not be found because the user_picture is the default
If I create a user_picture field it automatically adds field_ in front of the machine name.
Is it possible to restore the default field with the correct machine name ?
Solution
Instead of importing configuration as suggested previously, you could as an alternative, programmatically re-create the field. Here is some code that does that.
<?php
use Drupal\field\Entity\FieldConfig;
use Drupal\field\Entity\FieldStorageConfig;
// Create the user profile field and instance.
FieldStorageConfig::create([
'entity_type' => 'user',
'field_name' => 'user_picture',
'type' => 'image',
'translatable' => '0',
])->save();
FieldConfig::create([
'label' => 'User Picture',
'description' => '',
'field_name' => 'user_picture',
'entity_type' => 'user',
'bundle' => 'user',
'required' => 0,
])->save();
Assuming the code above is placed in a file called recreateUserPicture.php
that is stored in your docroot, you can run the following Drush command:
drush scr recreateUserPicture.php
Best of luck!
N.B.: An alternative answer (since the importing of configuration from the standard profile has a problem with having the field being available in Views UI).
OTHER TIPS
This can be handled using the install configuration that the standard profile holds. Easiest way would be using drupal's console, that would mean following these steps (from inside your docroot):
drupal config:import:single --file=core/profiles/standard/config/install/field.storage.user.user_picture.yml
drupal config:import:single --file=core/profiles/standard/config/install/field.field.user.user.user_picture.yml
drupal update:entities
In case you can't work on the terminal using drupal console, you can import these two configuration from the administrative interface. This can be found under the admin/config/development/configuration/single/import
URL (relative to your host's name).
From there, you need to import twice, one time the file storage configuration (contents of core/profiles/standard/config/install/field.storage.user.user_picture.yml) and the second would be the file configuration (contents of core/profiles/standard/config/install/field.field.user.user.user_picture.yml).
Hope this helps, good luck!