25e33e9774fcba8c63e8f8ef7f1c07481b61b392
[yaffs-website] / web / core / modules / aggregator / src / Plugin / Field / FieldFormatter / AggregatorTitleFormatter.php
1 <?php
2
3 namespace Drupal\aggregator\Plugin\Field\FieldFormatter;
4
5 use Drupal\Core\Field\FieldDefinitionInterface;
6 use Drupal\Core\Field\FieldItemListInterface;
7 use Drupal\Core\Field\FormatterBase;
8 use Drupal\Core\Form\FormStateInterface;
9 use Drupal\Core\Url;
10
11 /**
12  * Plugin implementation of the 'aggregator_title' formatter.
13  *
14  * @FieldFormatter(
15  *   id = "aggregator_title",
16  *   label = @Translation("Aggregator title"),
17  *   description = @Translation("Formats an aggregator item or feed title with an optional link."),
18  *   field_types = {
19  *     "string"
20  *   }
21  * )
22  */
23 class AggregatorTitleFormatter extends FormatterBase {
24   /**
25    * {@inheritdoc}
26    */
27   public static function defaultSettings() {
28     $options = parent::defaultSettings();
29
30     $options['display_as_link'] = TRUE;
31     return $options;
32   }
33
34   /**
35    * {@inheritdoc}
36    */
37   public function settingsForm(array $form, FormStateInterface $form_state) {
38     $form = parent::settingsForm($form, $form_state);
39
40     $form['display_as_link'] = [
41       '#type' => 'checkbox',
42       '#title' => $this->t('Link to URL'),
43       '#default_value' => $this->getSetting('display_as_link'),
44     ];
45
46     return $form;
47   }
48
49   /**
50    * {@inheritdoc}
51    */
52   public function viewElements(FieldItemListInterface $items, $langcode) {
53     $elements = [];
54
55     if ($items->getEntity()->getEntityTypeId() == 'aggregator_feed') {
56       $url_string = $items->getEntity()->getUrl();
57     }
58     else {
59       $url_string = $items->getEntity()->getLink();
60     }
61
62     foreach ($items as $delta => $item) {
63       if ($this->getSetting('display_as_link') && $url_string) {
64         $elements[$delta] = [
65             '#type' => 'link',
66             '#title' => $item->value,
67             '#url' => Url::fromUri($url_string),
68         ];
69       }
70       else {
71         $elements[$delta] = ['#markup' => $item->value];
72       }
73     }
74
75     return $elements;
76   }
77
78   /**
79    * {@inheritdoc}
80    */
81   public static function isApplicable(FieldDefinitionInterface $field_definition) {
82     return (($field_definition->getTargetEntityTypeId() === 'aggregator_item' || $field_definition->getTargetEntityTypeId() === 'aggregator_feed') && $field_definition->getName() === 'title');
83   }
84
85 }