Created
October 16, 2017 12:50
-
-
Save alexey-kuznetsov/5c90985a37e7bcffa602ddb54638553d to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
** | |
* 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