function opigno_forum_entity_presave in Opigno forum 8
Same name and namespace in other branches
- 3.x opigno_forum.module \opigno_forum_entity_presave()
Implements hook_entity_presave().
File
- ./
opigno_forum.module, line 24 - Contains opigno_forum.module.
Code
function opigno_forum_entity_presave(EntityInterface $entity) {
if ($entity
->getEntityTypeId() === 'group' && $entity
->bundle() === 'learning_path') {
/** @var \Drupal\group\Entity\Group $entity */
// Create a forum for the training
// if it is enabled and not already exists.
$enable_forum = $entity
->get('field_learning_path_enable_forum')
->getValue()[0]['value'];
$has_forum = !$entity
->get('field_learning_path_forum')
->isEmpty();
if ($enable_forum && !$has_forum) {
$forum = Term::create([
'vid' => 'forums',
'name' => $entity
->label(),
'parent' => 0,
]);
$forum
->save();
$entity
->set('field_learning_path_forum', [
'target_id' => $forum
->id(),
]);
}
}
// Update forum new learning path title.
if ($entity
->getEntityTypeId() === 'group' && $entity
->bundle() === 'learning_path' && !$entity
->isNew() && !$entity
->get('field_learning_path_forum')
->isEmpty()) {
$forum = $entity
->get('field_learning_path_forum')->target_id;
$forum = Term::load($forum);
if ($forum instanceof TermInterface) {
$new_name = $entity
->label();
$forum
->setName($new_name);
$forum
->save();
}
}
// Add notification about new post in a training forum.
if ($entity
->getEntityTypeId() === 'comment' && $entity
->bundle() === 'comment_forum') {
// If new post.
if ($entity
->isNew()) {
// Get post topic.
$topic = $entity
->getCommentedEntity();
if ($topic && !empty($topic->forum_tid)) {
// Get training id of the forum.
$db_connection = \Drupal::service('database');
$group_id = $db_connection
->select('group__field_learning_path_forum', 'lpf')
->fields('lpf', [
'entity_id',
])
->condition('field_learning_path_forum_target_id', $topic->forum_tid)
->execute()
->fetchField();
if ($group_id) {
$group = Group::load($group_id);
if ($group) {
// Get training members ids except current user.
$user = \Drupal::currentUser();
$uids = $db_connection
->select('group_content_field_data', 'gc')
->fields('gc', [
'entity_id',
])
->condition('type', 'learning_path-group_membership')
->condition('gid', $group_id)
->condition('entity_id', $user
->id(), '!=')
->execute()
->fetchCol();
if ($uids) {
$message = t('New forum post in training "@name"', [
'@name' => $group
->label(),
]);
$url = Url::fromRoute('entity.group.canonical', [
'group' => $group
->id(),
])
->toString();
foreach ($uids as $uid) {
$account = User::load($uid);
// Check user access to forum.
if ($account && _opigno_forum_access($topic->forum_tid, $account)) {
// Add notification about new post.
opigno_set_message($uid, $message, $url);
}
}
}
}
}
}
}
}
}