uw_ct_profile.module 2.46 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74
<?php

/**
 * @file
 * Profile module file.
 */

use Drupal\Core\Form\FormStateInterface;
use Drupal\node\Entity\Node;

/**
 * Implements hook_form_FORM_ID_alter().
 */
function uw_ct_profile_form_node_uw_ct_profile_form_alter(&$form, FormStateInterface $form_state, $form_id): void {
  $form['field_uw_ct_profile_contact']['widget'][0]['target_id']['#ajax'] = [
    'callback' => '_uw_ct_profile_node_form_callback',
    'event' => 'change',
    'wrapper' => $form['#id'],
  ];

  if ($form['field_uw_ct_profile_contact']['widget'][0]['target_id']) {
    foreach (_uw_ct_profile_alter_fields() as $profile_field => $contact_field) {
//      $form[$profile_field]['widget'][0]['value']['#value'] = $contact->$contact_field->value;
      $form[$profile_field]['widget'][0]['value']['#attributes']['readonly'] = 'readonly';
    }
  }
}

/**
 * Implements hook_form_FORM_ID_EDIT_FORM_alter().
 */
function uw_ct_profile_form_node_uw_ct_profile_edit_form_alter(&$form, FormStateInterface $form_state, $form_id): void {
  uw_ct_profile_form_node_uw_ct_profile_form_alter($form, $form_state, $form_id);
}

/**
 * Ajax call back function used in form alter.
 */
function _uw_ct_profile_node_form_callback(array &$form, FormStateInterface $form_state): array {
  $contact_nid = $form_state->getValue('field_uw_ct_profile_contact')[0]['target_id'];

  foreach (_uw_ct_profile_alter_fields() as $profile_field => $contact_field) {
    if ($contact_nid && is_numeric($contact_nid) && $contact = Node::load($contact_nid)) {
      // Copy value from the contact associated with this profile node.
      $form[$profile_field]['widget'][0]['value']['#value'] = $contact->$contact_field->value;
      // Set read only flag. Can't use #disabled (#states) since disabled fields
      // are not sent with submit (omitted). Validation will fail on req fields.
      $form[$profile_field]['widget'][0]['value']['#attributes']['readonly'] = 'readonly';
    }
    else {
      // Clear the read only flag, allow field to be edited.
      unset($form[$profile_field]['widget'][0]['value']['#attributes']['readonly']);
    }
  }

  return $form;
}

/**
 * Fields to sync.
 *
 * @return string[]
 *   Mapping of fields profile => contact.
 */
function _uw_ct_profile_alter_fields(): array {
  return [
    'title' => 'title',
    'field_uw_ct_profile_sort_name' => 'field_uw_ct_contact_sort_name',
    'field_uw_ct_profile_affiliation' => 'field_uw_ct_contact_affiliation',
    'field_uw_ct_profile_title' => 'field_uw_ct_contact_title',
  ];
}