Skip to content

Instantly share code, notes, and snippets.

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 alexey-kuznetsov/5c90985a37e7bcffa602ddb54638553d to your computer and use it in GitHub Desktop.
Save alexey-kuznetsov/5c90985a37e7bcffa602ddb54638553d to your computer and use it in GitHub Desktop.
**
* Implements hook_ENTITY_TYPE_create().
*/
function custom_node_create(Drupal\Core\Entity\EntityInterface $entity) {
if ($entity->bundle() == 'task') {
$lock = \Drupal::lock();
if (empty($entity->nid->getValue())) {
// Lock tables to avoid numbers duplicate
if (!$lock->acquire('insert_task')) {
$lock->wait('insert_task');
}
// Get the last task
$query = \Drupal::entityQuery('node')
->condition('status', 1)
->condition('type', 'task')
->sort('created', 'DESC')
->range(0, 1)->execute();
// Autofill task number
if (!empty($query)) {
$last_node = Node::load(array_pop($query));
if (empty($last_node->field_task_number->getValue())) {
$entity->field_task_number->value = "1-" . date('m');
} else {
if (date('m', $last_node->created->value) == date('m')) {
$previous_number = explode('-', $last_node->field_task_number->value)[0];
$entity->field_task_number->value = intval($previous_number) + 1 . "-" . date('m');
} else {
$entity->field_task_number->value = "1-" . date('m');
}
}
}
}
}
}
/**
* Implements hook_ENTITY_TYPE_insert().
*/
function custom_node_insert(Drupal\Core\Entity\EntityInterface $entity) {
if ($entity->bundle() == 'task') {
// Release lock acquired in hook_node_create
$lock = \Drupal::lock();
$lock->release('insert_task');
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment