function devel_generate_add_comments
Same name in other branches
- 6.x-1.x devel_generate.inc \devel_generate_add_comments()
- 7.x-1.x devel_generate/devel_generate.inc \devel_generate_add_comments()
- 4.x devel_generate/devel_generate.module \devel_generate_add_comments()
Create comments and add them to a node.
Parameters
\Drupal\node\NodeInterface $node: Node to add comments to.
\Drupal\Core\Field\FieldDefinitionInterface $field_definition: The field storage definition.
array $users: Array of users to assign comment authors.
int $max_comments: Max number of comments to generate per node.
int $title_length: Max length of the title of the comments.
1 call to devel_generate_add_comments()
- devel_generate_entity_insert in devel_generate/
devel_generate.module - Implements hook_entity_insert().
File
-
devel_generate/
devel_generate.module, line 79
Code
function devel_generate_add_comments(NodeInterface $node, FieldDefinitionInterface $field_definition, $users, $max_comments, $title_length = 8) {
$parents = array();
$field_name = $field_definition->getName();
$num_comments = mt_rand(1, $max_comments);
for ($i = 1; $i <= $num_comments; $i++) {
switch ($i % 3) {
case 0:
// No parent.
case 1:
// Top level parent.
$parents = \Drupal::entityQuery('comment')->condition('pid', 0)
->condition('entity_id', $node->id())
->condition('entity_type', 'node')
->condition('field_name', $field_name)
->range(0, 1)
->execute();
break;
case 2:
// Non top level parent.
$parents = \Drupal::entityQuery('comment')->condition('pid', 0, '>')
->condition('entity_id', $node->id())
->condition('entity_type', 'node')
->condition('field_name', $field_name)
->range(0, 1)
->execute();
break;
}
$random = new Random();
$stub = array(
'entity_type' => $node->getEntityTypeId(),
'entity_id' => $node->id(),
'field_name' => $field_name,
'name' => 'devel generate',
'mail' => 'devel_generate@example.com',
'timestamp' => mt_rand($node->getCreatedTime(), REQUEST_TIME),
'subject' => substr($random->sentences(mt_rand(2, $title_length), TRUE), 0, 63),
'uid' => $users[array_rand($users)],
'langcode' => $node->language()
->getId(),
);
if ($parents) {
$stub['pid'] = current($parents);
}
$comment = entity_create('comment', $stub);
//Populate all core fields on behalf of field.module
DevelGenerateBase::populateFields($comment);
$comment->save();
}
}