SubscriptionWidget.php in Simplenews 3.x
File
src/Plugin/Field/FieldWidget/SubscriptionWidget.php
View source
<?php
namespace Drupal\simplenews\Plugin\Field\FieldWidget;
use Drupal\Core\Entity\FieldableEntityInterface;
use Drupal\Core\Field\FieldItemListInterface;
use Drupal\Core\Field\Plugin\Field\FieldWidget\OptionsButtonsWidget;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Form\OptGroup;
use Drupal\simplenews\SubscriptionWidgetInterface;
class SubscriptionWidget extends OptionsButtonsWidget implements SubscriptionWidgetInterface {
protected $newsletterIds;
protected $hidden;
public function setAvailableNewsletterIds(array $newsletter_ids) {
$this->newsletterIds = $newsletter_ids;
}
public function setHidden($set = TRUE) {
$this->hidden = (bool) $set;
}
public function isHidden() {
return $this->hidden;
}
protected function getOptions(FieldableEntityInterface $entity) {
$options = parent::getOptions($entity);
if (isset($this->newsletterIds)) {
$options = array_intersect_key($options, array_flip($this->newsletterIds));
}
return $options;
}
protected function getSelectedOptions(FieldItemListInterface $items, $delta = 0) {
$flat_options = OptGroup::flattenOptions($this
->getOptions($items
->getEntity()));
$selected_options = [];
foreach ($items as $item) {
$value = $item->{$this->column};
if ($item->status == SIMPLENEWS_SUBSCRIPTION_STATUS_SUBSCRIBED && isset($flat_options[$value])) {
$selected_options[] = $value;
}
}
return $selected_options;
}
public function formElement(FieldItemListInterface $items, $delta, array $element, array &$form, FormStateInterface $form_state) {
if ($this
->isHidden()) {
foreach ($this->newsletterIds as $newsletter_id) {
$element[] = [
'target_id' => [
'#type' => 'value',
'#value' => $newsletter_id,
],
];
}
}
else {
$element = parent::formElement($items, $delta, $element, $form, $form_state);
}
return $element;
}
public function extractNewsletterIds(array $form_state_value, $selected = TRUE) {
$selected_ids = array_map(function ($item) {
return $item['target_id'];
}, $form_state_value);
return $selected ? $selected_ids : array_diff($this->newsletterIds, $selected_ids);
}
}