profile.module 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385
  1. <?php
  2. /**
  3. * @file
  4. * Support for configurable user profiles.
  5. */
  6. use Drupal\Core\Access\AccessResult;
  7. use Drupal\Core\Field\FieldDefinitionInterface;
  8. use Drupal\Core\Field\FieldItemListInterface;
  9. use Drupal\Core\Render\Element;
  10. use Drupal\Core\Session\AccountInterface;
  11. use Drupal\user\UserInterface;
  12. use Drupal\Core\Entity\Display\EntityViewDisplayInterface;
  13. use Drupal\Core\Entity\Entity\EntityFormDisplay;
  14. use Drupal\Core\Entity\EntityInterface;
  15. use Drupal\profile\Entity\Profile;
  16. use Drupal\profile\Entity\ProfileType;
  17. use Drupal\field\FieldConfigInterface;
  18. use Drupal\Core\Routing\RouteMatchInterface;
  19. use Drupal\Core\Form\FormStateInterface;
  20. use Drupal\Core\Url;
  21. /**
  22. * Implements hook_help().
  23. */
  24. function profile_help($route_name, RouteMatchInterface $route_match) {
  25. switch ($route_name) {
  26. case 'help.page.profile':
  27. $output = '<h3>' . t('About') . '</h3>';
  28. $output .= '<p>' . t('The Profile module provides a fieldable entity, that allows administrators to define different sets of fields for user profiles, which are then displayed in the <a href="@user">My Account</a> section. This permits users of a site to share more information about themselves, and can help community-based sites organize users around specific information.', ['@user' => Url::fromRoute('user.page')->toString()]) . '</p>';
  29. $output .= '<dl>';
  30. $output .= '<dt>' . t('Types of profiles') . '</dt>';
  31. $output .= '<dd>' . t('Profile types provide a way of grouping similar data for user profiles e.g. Personal information, Work etc. A default "Personal information type is provided. You may create more types and manage fields for each type from the <a href="@profile-types">Profile types</a> admin page. When creating a new profile type, you will be able to specify whether a user may create multiple profiles or make the profile form available when registering a new user.', ['@profile-types' => Url::fromRoute('entity.profile_type.collection')->toString()]) . '</dd>';
  32. $output .= '<dt>' . t('Creating profiles') . '</dt>';
  33. $output .= '<dd>' . t('A user will see tabs they have access to, when editing their main user account e.g. "Add personal information profile". The visibility of a tab depends on whether they can create multiple profiles or if they haven\'t created a profile of the type that doesn\'t allow multiple instances.') . '</dd>';
  34. $output .= '</dl>';
  35. return $output;
  36. }
  37. }
  38. /**
  39. * Implements hook_entity_field_access().
  40. */
  41. function profile_entity_field_access($operation, FieldDefinitionInterface $field_definition, AccountInterface $account, FieldItemListInterface $items = NULL) {
  42. if ($operation == 'view' && $items && $field_definition->getTargetEntityTypeId() == 'profile') {
  43. if ($field_definition instanceof FieldConfigInterface) {
  44. $is_private = $field_definition->getThirdPartySetting('profile', 'profile_private', FALSE);
  45. if ($is_private) {
  46. // Users may see their own private profile fields by default, so this
  47. // requires user granularity for caching.
  48. /** @var \Drupal\profile\Entity\ProfileInterface $profile */
  49. $profile = $items->getEntity();
  50. if ($account->id() === $profile->getOwnerId()) {
  51. return AccessResult::neutral();
  52. }
  53. return AccessResult::forbiddenIf(!$account->hasPermission('administer profile'));
  54. }
  55. }
  56. }
  57. return AccessResult::neutral();
  58. }
  59. /**
  60. * Implements hook_theme().
  61. */
  62. function profile_theme() {
  63. return [
  64. 'profile' => [
  65. 'render element' => 'elements',
  66. ],
  67. ];
  68. }
  69. /**
  70. * Prepares variables for profile templates.
  71. *
  72. * Default template: profile.html.twig.
  73. *
  74. * @param array $variables
  75. * An associative array containing:
  76. * - elements: An associative array containing rendered fields.
  77. * - attributes: HTML attributes for the containing element.
  78. */
  79. function template_preprocess_profile(array &$variables) {
  80. /** @var Drupal\profile\Entity\ProfileInterface $profile */
  81. $profile = $variables['elements']['#profile'];
  82. $variables['profile'] = $profile;
  83. $variables['url'] = $profile->id() ? $profile->toUrl() : FALSE;
  84. // Helpful $content variable for templates.
  85. $variables['content'] = [];
  86. foreach (Element::children($variables['elements']) as $key) {
  87. $variables['content'][$key] = $variables['elements'][$key];
  88. }
  89. }
  90. /**
  91. * Implements hook_user_view().
  92. */
  93. function profile_user_view(array &$build, UserInterface $account, EntityViewDisplayInterface $display, $view_mode) {
  94. // Iterate through each bundle and see if it's component exists.
  95. foreach (ProfileType::loadMultiple() as $bundle) {
  96. $component_key = 'profile_' . $bundle->id();
  97. if ($display->getComponent($component_key)) {
  98. // Embed the view of active profiles for profile type.
  99. $build[$component_key] = [
  100. '#type' => 'view',
  101. '#name' => 'profiles',
  102. '#display_id' => 'user_view',
  103. '#arguments' => [$account->id(), $bundle->id(), 1],
  104. '#embed' => TRUE,
  105. '#title' => $bundle->label(),
  106. '#pre_render' => [
  107. ['\Drupal\views\Element\View', 'preRenderViewElement'],
  108. 'profile_views_add_title_pre_render',
  109. ],
  110. ];
  111. }
  112. }
  113. }
  114. /**
  115. * Implements hook_entity_extra_field_info().
  116. */
  117. function profile_entity_extra_field_info() {
  118. $extra = [];
  119. // Add each profile type as an extra field for display. Not enabled by default
  120. // as many sites will not need this and it otherwise also gets added
  121. // automatically to other view modes.
  122. /** @var \Drupal\profile\Entity\ProfileType $bundle */
  123. foreach (ProfileType::loadMultiple() as $bundle) {
  124. $extra['user']['user']['display']['profile_' . $bundle->id()] = array(
  125. 'label' => $bundle->label(),
  126. 'description' => t('Display @type profiles', ['@type' => $bundle->label()]),
  127. 'weight' => 10,
  128. 'visible' => FALSE,
  129. );
  130. }
  131. return $extra;
  132. }
  133. /**
  134. * Implements hook_user_delete().
  135. */
  136. function profile_user_delete(EntityInterface $entity) {
  137. $list = \Drupal::entityTypeManager()
  138. ->getStorage('profile')
  139. ->loadByProperties([
  140. 'uid' => $entity->id(),
  141. ]);
  142. foreach ($list as $profile) {
  143. $profile->delete();
  144. }
  145. }
  146. /**
  147. * Implements hook_form_FORM_ID_alter().
  148. */
  149. function profile_form_field_config_edit_form_alter(&$form, FormStateInterface $form_state, $form_id) {
  150. $field = $form_state->getFormObject()->getEntity();
  151. if ($field->getTargetEntityTypeId() != 'profile') {
  152. return;
  153. }
  154. $form['field']['profile']['profile_private'] = [
  155. '#type' => 'checkbox',
  156. '#title' => t('This is a private field.'),
  157. '#default_value' => $field->getThirdPartySetting('profile', 'profile_private', FALSE),
  158. ];
  159. $form['actions']['submit']['#submit'][] = 'profile_form_field_config_edit_form_submit';
  160. }
  161. /**
  162. * Form submission handler for profile_form_field_config_edit_form_alter.
  163. *
  164. * @param array $form
  165. * The form array.
  166. * @param FormStateInterface $form_state
  167. * The form state.
  168. */
  169. function profile_form_field_config_edit_form_submit(array $form, FormStateInterface $form_state) {
  170. $field = $form_state->getFormObject()->getEntity();
  171. $form_fields = &$form_state->getValues();
  172. // If the private option is checked, update settings.
  173. if ($form_fields['profile_private']) {
  174. $field->setThirdPartySetting('profile', 'profile_private', TRUE);
  175. $field->save();
  176. }
  177. else {
  178. $field->unsetThirdPartySetting('profile', 'profile_private');
  179. $field->save();
  180. }
  181. }
  182. /**
  183. * Implements hook_form_FORM_ID_alter().
  184. *
  185. * Add available profile forms to the user registration form.
  186. */
  187. function profile_form_user_register_form_alter(&$form, FormStateInterface $form_state) {
  188. $attached_profile_form = FALSE;
  189. $weight = 90;
  190. /** @var ProfileType[] $profile_types */
  191. $profile_types = ProfileType::loadMultiple();
  192. foreach ($profile_types as $profile_type) {
  193. $instances = array_filter(\Drupal::service('entity_field.manager')->getFieldDefinitions('profile', $profile_type->id()), function ($field_definition) {
  194. return $field_definition instanceof FieldConfigInterface;
  195. });
  196. if ($profile_type->getRegistration() === TRUE && count($instances)) {
  197. $property = ['profiles', $profile_type->id()];
  198. $profile = $form_state->get($property);
  199. if (empty($profile)) {
  200. $profile = Profile::create([
  201. 'type' => $profile_type->id(),
  202. 'langcode' => $profile_type->language() ? $profile_type->language() : \Drupal::languageManager()->getDefaultLanguage()->getId(),
  203. ]);
  204. // Attach profile entity form.
  205. $form_state->set($property, $profile);
  206. }
  207. $form_state->set('form_display_' . $profile_type->id(), EntityFormDisplay::collectRenderDisplay($profile, 'default'));
  208. $form['entity_' . $profile_type->id()] = [
  209. '#type' => 'details',
  210. '#title' => $profile_type->label(),
  211. '#tree' => TRUE,
  212. '#parents' => ['entity_' . $profile_type->id()],
  213. '#weight' => ++$weight,
  214. '#open' => TRUE,
  215. ];
  216. // @see https://www.drupal.org/node/2871480.
  217. if (\Drupal::moduleHandler()->moduleExists('field_group')) {
  218. $context = [
  219. 'entity_type' => $profile->getEntityTypeId(),
  220. 'bundle' => $profile->bundle(),
  221. 'entity' => $profile,
  222. 'context' => 'form',
  223. 'display_context' => 'form',
  224. 'mode' => 'default',
  225. ];
  226. field_group_attach_groups($form['entity_' . $profile_type->id()], $context);
  227. $form['entity_' . $profile_type->id()]['#pre_render'][] = 'field_group_form_pre_render';
  228. }
  229. $form_state
  230. ->get('form_display_' . $profile_type->id())
  231. ->buildForm($profile, $form['entity_' . $profile_type->id()], $form_state);
  232. $attached_profile_form = TRUE;
  233. }
  234. }
  235. if ($attached_profile_form) {
  236. $form['actions']['submit']['#validate'][] = 'profile_form_user_register_form_validate';
  237. $form['actions']['submit']['#submit'][] = 'profile_form_user_register_form_submit';
  238. }
  239. }
  240. /**
  241. * Extra form validation handler for the user registration form.
  242. */
  243. function profile_form_user_register_form_validate(array &$form, FormStateInterface $form_state) {
  244. $profiles = $form_state->get('profiles');
  245. if (!empty($profiles)) {
  246. foreach ($profiles as $bundle => $entity) {
  247. /** @var \Drupal\Core\Entity\Display\EntityFormDisplayInterface $form_display */
  248. $form_display = $form_state->get('form_display_' . $bundle);
  249. if (isset($form['entity_' . $bundle])) {
  250. $form_display->extractFormValues($entity, $form['entity_' . $bundle], $form_state);
  251. $form_display->validateFormValues($entity, $form['entity_' . $bundle], $form_state);
  252. }
  253. }
  254. }
  255. // Entity was validated in entityFormValidate(). This will prevent validation
  256. // exception from being thrown.
  257. $form_state->getFormObject()->validateForm($form, $form_state);
  258. }
  259. /**
  260. * Extra form submission handler for the user registration form.
  261. */
  262. function profile_form_user_register_form_submit(array &$form, FormStateInterface $form_state) {
  263. /** @var \Drupal\Core\Session\AccountInterface $account */
  264. $account = $form_state->getFormObject()->getEntity();
  265. $profiles = $form_state->get('profiles');
  266. if (!empty($profiles)) {
  267. foreach ($profiles as $bundle => $entity) {
  268. $entity->setOwnerId($account->id());
  269. $entity->setActive(TRUE);
  270. $entity->save();
  271. }
  272. }
  273. }
  274. /**
  275. * Pre render callback for profile embedded views to ensure a title is set.
  276. * @param $element
  277. *
  278. * @return mixed
  279. */
  280. function profile_views_add_title_pre_render($element) {
  281. /** @var \Drupal\views\ViewExecutable $view */
  282. if (isset($element['#title'])) {
  283. $view = $element['view_build']['#view'];
  284. if (!empty($view->result)) {
  285. $view->setTitle($element['#title']);
  286. }
  287. }
  288. return $element;
  289. }
  290. /**
  291. * Implements hook_preprocess_HOOK().
  292. */
  293. function profile_preprocess_views_view(&$variables) {
  294. // We have to manually add back the title since it was removed by Views.
  295. // @see template_preprocess_views_view()
  296. /** @var \Drupal\views\ViewExecutable $view */
  297. $view = $variables['view'];
  298. if ($view->storage->id() == 'profiles' && !empty($view->result)) {
  299. // Test access to the profile.
  300. /** @var \Drupal\profile\Entity\profile $entity */
  301. $entity = reset($view->result)->_entity;
  302. if ($entity->access('view')) {
  303. $variables['title'] = $view->getTitle();
  304. }
  305. }
  306. }
  307. /**
  308. * Implements hook_views_data_alter().
  309. *
  310. * Adds a relationship from the user table to its' profile entity.
  311. */
  312. function profile_views_data_alter(&$data) {
  313. $data['users_field_data']['profile']['relationship'] = [
  314. 'title' => t('Profile'),
  315. 'label' => t('Profile'),
  316. 'group' => 'User',
  317. 'help' => t('Reference to the profile of a user.'),
  318. 'id' => 'standard',
  319. 'base' => 'profile',
  320. 'base field' => 'uid',
  321. 'field' => 'uid',
  322. ];
  323. $data['users_field_data']['profile_type']['relationship'] = [
  324. 'title' => t('Profile Type'),
  325. 'label' => t('Profile Type'),
  326. 'group' => 'User',
  327. 'help' => t('Reference to a specific profile type of a user.'),
  328. 'id' => 'profile_relationship',
  329. 'base' => 'profile',
  330. 'base field' => 'uid',
  331. 'field' => 'uid',
  332. ];
  333. }
  334. /**
  335. * Implements hook_theme_suggestions_HOOK().
  336. */
  337. function profile_theme_suggestions_profile(array $variables) {
  338. $original = $variables['theme_hook_original'];
  339. $entity = $variables['elements']['#profile'];
  340. $sanitized_view_mode = strtr($variables['elements']['#view_mode'], '.', '_');
  341. $suggestions = [];
  342. $suggestions[] = $original;
  343. $suggestions[] = $original . '__' . $sanitized_view_mode;
  344. $suggestions[] = $original . '__' . $entity->bundle();
  345. $suggestions[] = $original . '__' . $entity->bundle() . '__' . $sanitized_view_mode;
  346. $suggestions[] = $original . '__' . $entity->id();
  347. $suggestions[] = $original . '__' . $entity->id() . '__' . $sanitized_view_mode;
  348. return $suggestions;
  349. }