profile.module 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345
  1. <?php
  2. /**
  3. * @file
  4. * Support for configurable user profiles.
  5. */
  6. use Drupal\user\UserInterface;
  7. use Drupal\Core\Entity\Display\EntityViewDisplayInterface;
  8. use Drupal\Core\Entity\Entity\EntityFormDisplay;
  9. use Drupal\Core\Entity\EntityInterface;
  10. use Drupal\profile\Entity\Profile;
  11. use Drupal\profile\Entity\ProfileType;
  12. use Drupal\field\FieldConfigInterface;
  13. use Drupal\Core\Routing\RouteMatchInterface;
  14. use Drupal\Core\Form\FormStateInterface;
  15. use Drupal\Core\Url;
  16. /**
  17. * Denotes that the profile is not active.
  18. */
  19. const PROFILE_NOT_ACTIVE = 0;
  20. /**
  21. * Denotes that the profile is active.
  22. */
  23. const PROFILE_ACTIVE = 1;
  24. /**
  25. * Denotes that the profile is not default.
  26. */
  27. const PROFILE_NOT_DEFAULT = 0;
  28. /**
  29. * Denotes that the profile is default.
  30. */
  31. const PROFILE_DEFAULT = 1;
  32. /**
  33. * Implements hook_help().
  34. */
  35. function profile_help($route_name, RouteMatchInterface $route_match) {
  36. switch ($route_name) {
  37. case 'help.page.profile':
  38. $output = '<h3>' . t('About') . '</h3>';
  39. $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')]) . '</p>';
  40. $output .= '<dl>';
  41. $output .= '<dt>' . t('Types of profiles') . '</dt>';
  42. $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')]) . '</dd>';
  43. $output .= '<dt>' . t('Creating profiles') . '</dt>';
  44. $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>';
  45. $output .= '</dl>';
  46. return $output;
  47. }
  48. }
  49. /**
  50. * Implements hook_theme().
  51. */
  52. function profile_theme() {
  53. return [
  54. 'profile' => [
  55. 'render element' => 'elements',
  56. ],
  57. ];
  58. }
  59. /**
  60. * Prepares variables for profile templates.
  61. *
  62. * Default template: profile.html.twig.
  63. *
  64. * @param array $variables
  65. * An associative array containing:
  66. * - elements: An associative array containing rendered fields.
  67. * - attributes: HTML attributes for the containing element.
  68. */
  69. function template_preprocess_profile(array &$variables) {
  70. /** @var Drupal\profile\Entity\ProfileInterface $profile */
  71. $profile = $variables['elements']['#profile'];
  72. $variables['profile'] = $profile;
  73. $variables['url'] = $profile->toUrl();
  74. // Helpful $content variable for templates.
  75. $variables['content'] = [];
  76. foreach (\Drupal\Core\Render\Element::children($variables['elements']) as $key) {
  77. $variables['content'][$key] = $variables['elements'][$key];
  78. }
  79. }
  80. /**
  81. * Implements hook_user_view().
  82. */
  83. function profile_user_view(array &$build, UserInterface $account, EntityViewDisplayInterface $display, $view_mode) {
  84. // Iterate through each bundle and see if it's component exists.
  85. foreach (ProfileType::loadMultiple() as $bundle) {
  86. $component_key = 'profile_' . $bundle->id();
  87. if ($display->getComponent($component_key)) {
  88. // Embed the view of active profiles for profile type.
  89. $build[$component_key] = [
  90. '#type' => 'view',
  91. '#name' => 'profiles',
  92. '#display_id' => 'user_view',
  93. '#arguments' => [$account->id(), $bundle->id(), 1],
  94. '#embed' => TRUE,
  95. '#title' => $bundle->label(),
  96. '#pre_render' => [
  97. ['\Drupal\views\Element\View', 'preRenderViewElement'],
  98. 'profile_views_add_title_pre_render',
  99. ],
  100. ];
  101. }
  102. }
  103. }
  104. /**
  105. * Implements hook_entity_extra_field_info().
  106. */
  107. function profile_entity_extra_field_info() {
  108. $extra = [];
  109. // Add each profile type as an extra field for display. Enabled by default.
  110. foreach (ProfileType::loadMultiple() as $bundle) {
  111. $extra['user']['user']['display']['profile_' . $bundle->id()] = array(
  112. 'label' => $bundle->label(),
  113. 'description' => t('Display @type profiles', ['@type' => $bundle->label()]),
  114. 'weight' => 10,
  115. 'visible' => TRUE,
  116. );
  117. }
  118. return $extra;
  119. }
  120. /**
  121. * Implements hook_user_delete().
  122. */
  123. function profile_user_delete(EntityInterface $entity) {
  124. $list = \Drupal::entityTypeManager()
  125. ->getStorage('profile')
  126. ->loadByProperties([
  127. 'uid' => $entity->id(),
  128. ]);
  129. foreach ($list as $profile) {
  130. $profile->delete();
  131. }
  132. }
  133. /**
  134. * Implements hook_form_FORM_ID_alter().
  135. */
  136. function profile_form_field_config_edit_form_alter(&$form, FormStateInterface $form_state, $form_id) {
  137. $field = $form_state->getFormObject()->getEntity();
  138. if ($field->getTargetEntityTypeId() != 'profile') {
  139. return;
  140. }
  141. $form['field']['profile']['profile_private'] = [
  142. '#type' => 'checkbox',
  143. '#title' => t('This is a private field.'),
  144. '#default_value' => $field->getThirdPartySetting('profile', 'profile_private', FALSE),
  145. ];
  146. $form['actions']['submit']['#submit'][] = 'profile_form_field_config_edit_form_submit';
  147. }
  148. /**
  149. * Form submission handler for profile_form_field_config_edit_form_alter.
  150. *
  151. * @param array $form
  152. * The form array.
  153. * @param FormStateInterface $form_state
  154. * The form state.
  155. */
  156. function profile_form_field_config_edit_form_submit(array $form, FormStateInterface $form_state) {
  157. $field = $form_state->getFormObject()->getEntity();
  158. $form_fields = &$form_state->getValues();
  159. // If the private option is checked, update settings.
  160. if ($form_fields['profile_private']) {
  161. $field->setThirdPartySetting('profile', 'profile_private', TRUE);
  162. $field->save();
  163. }
  164. else {
  165. $field->unsetThirdPartySetting('profile', 'profile_private');
  166. $field->save();
  167. }
  168. }
  169. /**
  170. * Implements hook_form_FORM_ID_alter().
  171. *
  172. * Add available profile forms to the user registration form.
  173. */
  174. function profile_form_user_register_form_alter(&$form, FormStateInterface $form_state) {
  175. $attached_profile_form = FALSE;
  176. $weight = 90;
  177. /** @var ProfileType[] $profile_types */
  178. $profile_types = ProfileType::loadMultiple();
  179. foreach ($profile_types as $profile_type) {
  180. $instances = array_filter(\Drupal::service('entity_field.manager')->getFieldDefinitions('profile', $profile_type->id()), function ($field_definition) {
  181. return $field_definition instanceof FieldConfigInterface;
  182. });
  183. if ($profile_type->getRegistration() === TRUE && count($instances)) {
  184. $property = ['profiles', $profile_type->id()];
  185. $profile = $form_state->get($property);
  186. if (empty($profile)) {
  187. $profile = Profile::create([
  188. 'type' => $profile_type->id(),
  189. 'langcode' => $profile_type->language() ?
  190. $profile_type->language() : \Drupal::languageManager()->getDefaultLanguage()->getId(),
  191. ]);
  192. // Attach profile entity form.
  193. $form_state->set($property, $profile);
  194. }
  195. $form_state->set('form_display_' . $profile_type->id(), EntityFormDisplay::collectRenderDisplay($profile, 'default'));
  196. $form['entity_' . $profile_type->id()] = [
  197. '#type' => 'details',
  198. '#title' => $profile_type->label(),
  199. '#tree' => TRUE,
  200. '#parents' => ['entity_' . $profile_type->id()],
  201. '#weight' => ++$weight,
  202. '#open' => TRUE,
  203. ];
  204. $form_state
  205. ->get('form_display_' . $profile_type->id())
  206. ->buildForm($profile, $form['entity_' . $profile_type->id()], $form_state);
  207. $attached_profile_form = TRUE;
  208. }
  209. }
  210. if ($attached_profile_form) {
  211. $form['actions']['submit']['#validate'][] = 'profile_form_user_register_form_validate';
  212. $form['actions']['submit']['#submit'][] = 'profile_form_user_register_form_submit';
  213. }
  214. }
  215. /**
  216. * Extra form validation handler for the user registration form.
  217. */
  218. function profile_form_user_register_form_validate(array &$form, FormStateInterface $form_state) {
  219. $profiles = $form_state->get('profiles');
  220. if (!empty($profiles)) {
  221. foreach ($profiles as $bundle => $entity) {
  222. /** @var \Drupal\Core\Entity\Display\EntityFormDisplayInterface $form_display */
  223. $form_display = $form_state->get('form_display_' . $bundle);
  224. $form_display->extractFormValues($entity, $form['entity_' . $bundle], $form_state);
  225. $form_display->validateFormValues($entity, $form['entity_' . $bundle], $form_state);
  226. }
  227. }
  228. // Entity was validated in entityFormValidate(). This will prevent validation
  229. // exception from being thrown.
  230. $form_state->getFormObject()->getEntity()->validate();
  231. }
  232. /**
  233. * Extra form submission handler for the user registration form.
  234. */
  235. function profile_form_user_register_form_submit(array &$form, FormStateInterface $form_state) {
  236. /** @var \Drupal\Core\Session\AccountInterface $account */
  237. $account = $form_state->getFormObject()->getEntity();
  238. $profiles = $form_state->get('profiles');
  239. if (!empty($profiles)) {
  240. foreach ($profiles as $bundle => $entity) {
  241. $entity->setOwnerId($account->id());
  242. $entity->setActive(TRUE);
  243. $entity->save();
  244. }
  245. }
  246. }
  247. /**
  248. * Pre render callback for profile embedded views to ensure a title is set.
  249. * @param $element
  250. *
  251. * @return mixed
  252. */
  253. function profile_views_add_title_pre_render($element) {
  254. /** @var \Drupal\views\ViewExecutable $view */
  255. if (isset($element['#title'])) {
  256. $view = $element['view_build']['#view'];
  257. $view->setTitle($element['#title']);
  258. }
  259. return $element;
  260. }
  261. /**
  262. * Implements hook_preprocess_HOOK().
  263. */
  264. function profile_preprocess_views_view(&$variables) {
  265. // We have to manually add back the title since it was removed by Views.
  266. // @see template_preprocess_views_view()
  267. /** @var \Drupal\views\ViewExecutable $view */
  268. $view = $variables['view'];
  269. if ($view->storage->id() == 'profiles' && !empty($view->result)) {
  270. // Test access to the profile.
  271. /** @var \Drupal\profile\Entity\profile $entity */
  272. $entity = reset($view->result)->_entity;
  273. if ($entity->access('view')) {
  274. $variables['title'] = $view->getTitle();
  275. }
  276. }
  277. }
  278. /**
  279. * Implements hook_views_data_alter().
  280. *
  281. * Adds a relationship from the user table to its' profile entity.
  282. */
  283. function profile_views_data_alter(&$data) {
  284. $data['users_field_data']['profile']['relationship'] = [
  285. 'title' => t('Profile'),
  286. 'label' => t('Profile'),
  287. 'group' => 'User',
  288. 'help' => t('Reference to the profile of a user.'),
  289. 'id' => 'standard',
  290. 'base' => 'profile',
  291. 'base field' => 'uid',
  292. 'field' => 'uid',
  293. ];
  294. }
  295. /**
  296. * Implements hook_theme_suggestions_HOOK().
  297. */
  298. function profile_theme_suggestions_profile(array $variables) {
  299. $original = $variables['theme_hook_original'];
  300. $entity = $variables['elements']['#profile'];
  301. $sanitized_view_mode = strtr($variables['elements']['#view_mode'], '.', '_');
  302. $suggestions = [];
  303. $suggestions[] = $original;
  304. $suggestions[] = $original . '__' . $sanitized_view_mode;
  305. $suggestions[] = $original . '__' . $entity->bundle();
  306. $suggestions[] = $original . '__' . $entity->bundle() . '__' . $sanitized_view_mode;
  307. $suggestions[] = $original . '__' . $entity->id();
  308. $suggestions[] = $original . '__' . $entity->id() . '__' . $sanitized_view_mode;
  309. return $suggestions;
  310. }