View source
<?php
namespace Drupal\comment\Plugin\Field\FieldWidget;
use Drupal\comment\Plugin\Field\FieldType\CommentItemInterface;
use Drupal\Component\Utility\Html;
use Drupal\Core\Field\FieldItemListInterface;
use Drupal\Core\Field\WidgetBase;
use Drupal\Core\Form\FormStateInterface;
class CommentWidget extends WidgetBase {
public function formElement(FieldItemListInterface $items, $delta, array $element, array &$form, FormStateInterface $form_state) {
$entity = $items
->getEntity();
$element['status'] = array(
'#type' => 'radios',
'#title' => t('Comments'),
'#title_display' => 'invisible',
'#default_value' => $items->status,
'#options' => array(
CommentItemInterface::OPEN => t('Open'),
CommentItemInterface::CLOSED => t('Closed'),
CommentItemInterface::HIDDEN => t('Hidden'),
),
CommentItemInterface::OPEN => array(
'#description' => t('Users with the "Post comments" permission can post comments.'),
),
CommentItemInterface::CLOSED => array(
'#description' => t('Users cannot post comments, but existing comments will be displayed.'),
),
CommentItemInterface::HIDDEN => array(
'#description' => t('Comments are hidden from view.'),
),
);
if (!$this
->isDefaultValueWidget($form_state) && !$items->comment_count) {
$element['status'][CommentItemInterface::HIDDEN]['#access'] = FALSE;
$element['status'][CommentItemInterface::CLOSED]['#description'] = t('Users cannot post comments.');
}
if (isset($form['advanced'])) {
$field_default_values = $this->fieldDefinition
->getDefaultValue($entity);
$element['#title'] = $this
->t('Comment settings');
$element += array(
'#type' => 'details',
'#open' => $items->status != $field_default_values[0]['status'],
'#group' => 'advanced',
'#attributes' => array(
'class' => array(
'comment-' . Html::getClass($entity
->getEntityTypeId()) . '-settings-form',
),
),
'#attached' => array(
'library' => array(
'comment/drupal.comment',
),
),
);
}
return $element;
}
public function massageFormValues(array $values, array $form, FormStateInterface $form_state) {
foreach ($values as &$value) {
$value += array(
'cid' => 0,
'last_comment_timestamp' => 0,
'last_comment_name' => '',
'last_comment_uid' => 0,
'comment_count' => 0,
);
}
return $values;
}
}