'_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']['#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', ]; } /** * Implements hook_entity_presave(). */ function uw_ct_profile_entity_presave(EntityInterface $entity) { // Sync image only for profile entity, only when entity is created, there is // contact link provided, and image field is empty. if ($entity->bundle() === 'uw_ct_profile' && $entity->isNew() && $entity->field_uw_ct_profile_contact->entity && !$entity->field_uw_ct_profile_image->value ) { // Get contact entity from Link with contact field. $contact = $entity->field_uw_ct_profile_contact->entity; // If contact has attached image. if ($image = $contact->field_uw_ct_contact_image->entity) { // Update image field of profile with values from contact. $entity->field_uw_ct_profile_image->target_id = $image->id(); } } }