3 namespace Drupal\comment\Plugin\Field\FieldWidget;
5 use Drupal\comment\Plugin\Field\FieldType\CommentItemInterface;
6 use Drupal\Component\Utility\Html;
7 use Drupal\Core\Field\FieldItemListInterface;
8 use Drupal\Core\Field\WidgetBase;
9 use Drupal\Core\Form\FormStateInterface;
12 * Provides a default comment widget.
15 * id = "comment_default",
16 * label = @Translation("Comment"),
22 class CommentWidget extends WidgetBase {
27 public function formElement(FieldItemListInterface $items, $delta, array $element, array &$form, FormStateInterface $form_state) {
28 $entity = $items->getEntity();
30 $element['status'] = [
32 '#title' => t('Comments'),
33 '#title_display' => 'invisible',
34 '#default_value' => $items->status,
36 CommentItemInterface::OPEN => t('Open'),
37 CommentItemInterface::CLOSED => t('Closed'),
38 CommentItemInterface::HIDDEN => t('Hidden'),
40 CommentItemInterface::OPEN => [
41 '#description' => t('Users with the "Post comments" permission can post comments.'),
43 CommentItemInterface::CLOSED => [
44 '#description' => t('Users cannot post comments, but existing comments will be displayed.'),
46 CommentItemInterface::HIDDEN => [
47 '#description' => t('Comments are hidden from view.'),
50 // If the entity doesn't have any comments, the "hidden" option makes no
51 // sense, so don't even bother presenting it to the user unless this is the
52 // default value widget on the field settings form.
53 if (!$this->isDefaultValueWidget($form_state) && !$items->comment_count) {
54 $element['status'][CommentItemInterface::HIDDEN]['#access'] = FALSE;
55 // Also adjust the description of the "closed" option.
56 $element['status'][CommentItemInterface::CLOSED]['#description'] = t('Users cannot post comments.');
58 // If the advanced settings tabs-set is available (normally rendered in the
59 // second column on wide-resolutions), place the field as a details element
61 if (isset($form['advanced'])) {
62 // Get default value from the field.
63 $field_default_values = $this->fieldDefinition->getDefaultValue($entity);
65 // Override widget title to be helpful for end users.
66 $element['#title'] = $this->t('Comment settings');
70 // Open the details when the selected value is different to the stored
71 // default values for the field.
72 '#open' => ($items->status != $field_default_values[0]['status']),
73 '#group' => 'advanced',
75 'class' => ['comment-' . Html::getClass($entity->getEntityTypeId()) . '-settings-form'],
78 'library' => ['comment/drupal.comment'],
89 public function massageFormValues(array $values, array $form, FormStateInterface $form_state) {
90 // Add default values for statistics properties because we don't want to
92 foreach ($values as &$value) {
95 'last_comment_timestamp' => 0,
96 'last_comment_name' => '',
97 'last_comment_uid' => 0,