PollChoiceDefaultWidget.php in Poll 8
File
src/Plugin/Field/FieldWidget/PollChoiceDefaultWidget.php
View source
<?php
namespace Drupal\poll\Plugin\Field\FieldWidget;
use Drupal\Core\Field\FieldDefinitionInterface;
use Drupal\Core\Field\FieldItemListInterface;
use Drupal\Core\Field\WidgetBase;
use Drupal\Core\Form\FormStateInterface;
class PollChoiceDefaultWidget extends WidgetBase {
const VOTE_DEFAULT_VALUE = 1;
public function formElement(FieldItemListInterface $items, $delta, array $element, array &$form, FormStateInterface $form_state) {
$langcode = $this
->getCurrentLangcode($form_state, $items);
$choice = $items[$delta]->entity;
if ($choice) {
if ($choice
->language()
->getId() != $langcode && !$choice
->hasTranslation($langcode)) {
$choice
->addTranslation($langcode, $choice
->toArray());
}
$choice = $choice
->getTranslation($langcode);
}
$element['target_id'] = array(
'#type' => 'value',
'#value' => $choice ? $choice
->id() : NULL,
);
$element['langcode'] = array(
'#type' => 'value',
'#value' => $langcode,
);
$element['choice'] = array(
'#type' => 'textfield',
'#placeholder' => t('Choice'),
'#empty_value' => '',
'#maxlength' => 255,
'#default_value' => $choice ? $choice->choice->value : NULL,
'#prefix' => '<div class="container-inline">',
);
return $element;
}
protected function getCurrentLangcode(FormStateInterface $form_state, FieldItemListInterface $items) {
return $form_state
->get('langcode') ?: $items
->getEntity()
->language()
->getId();
}
public static function isApplicable(FieldDefinitionInterface $field_definition) {
return $field_definition
->getTargetEntityTypeId() == 'poll' && $field_definition
->getName() == 'choice';
}
public function massageFormValues(array $values, array $form, FormStateInterface $form_state) {
foreach ($values as $delta => &$item_values) {
$entity_type_manager = \Drupal::entityTypeManager();
$storage = $entity_type_manager
->getStorage('poll_choice');
$langcode = $item_values['langcode'];
if (empty($item_values['choice'])) {
unset($values[$delta]);
continue;
}
$choice = !empty($item_values['target_id']) ? $storage
->load($item_values['target_id']) : $storage
->create([
'langcode' => $langcode,
]);
if ($choice
->language()
->getId() != $langcode && !$choice
->hasTranslation($langcode)) {
$choice
->addTranslation($langcode, $choice
->toArray());
}
$choice = $choice
->getTranslation($langcode);
if ($choice
->isNew() || $item_values['choice'] != $choice->choice->value) {
$choice->choice->value = $item_values['choice'];
$choice
->needsSaving(TRUE);
}
unset($item_values['target_id'], $item_values['choice'], $item_values['langcode']);
$item_values['entity'] = $choice;
}
return $values;
}
}