Skip to content

Instantly share code, notes, and snippets.

@Greg-Boggs
Created September 15, 2021 23:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Greg-Boggs/f63a4161d93d8746d82ed904e6a664d4 to your computer and use it in GitHub Desktop.
Save Greg-Boggs/f63a4161d93d8746d82ed904e6a664d4 to your computer and use it in GitHub Desktop.
Save the fields from the previous node to the new node when they have the same title and presenter
<?php
/**
* Implements hook_ENTITY_TYPE_presave().
*
* Prefill cost information for events if a previous event matches the same name and presenter.
*/
function libevents_node_presave(EntityInterface $node) {
$title = '';
$presenter = '';
try {
if ($node->isNew()) {
if ($node->getType() == 'event') {
// Get the current title and presenter
$title = $node->getTitle();
if ($node->get('field_search_tags')
->referencedEntities()[0]) {
$presenter = $node->get('field_search_tags')
->referencedEntities()[0]->getTitle();
}
// Get the most recent node with the same title and presenter.
$query = \Drupal::entityQuery('node')
->condition('title', $title, '=')
->condition('field_search_tags.entity.title', $presenter)
->sort('nid', 'DESC')
->range(0, 1);
$nid = $query->execute();
// If there is a match, preset the event financial fields
if (isset($nid) && !empty($nid)) {
$prev_node = Node::load(reset($nid));
if($node->hasField('field_program_cost_code') && $prev_node->hasField('field_program_cost_code')) {
$node->field_program_cost_code->target_id = $prev_node->get('field_program_cost_code')->target_id;
}
$node->set('field_professional_amount', $prev_node->get('field_professional_amount')->getValue());
$node->set('field_professional_quantity', $prev_node->get('field_professional_quantity')->getValue());
$node->set('field_preparation_quantity', $prev_node->get('field_preparation_quantity')->getValue());
$node->set('field_preparation_amount', $prev_node->get('field_preparation_amount')->getValue());
$node->set('field_travel_fee_amount', $prev_node->get('field_travel_fee_amount')->getValue());
$node->set('field_free_amount', $prev_node->get('field_free_amount')->getValue());
}
}
}
} catch (Exception $e) {
\Drupal::messenger()->addError($e->getMessage());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment