de8f703508dc346037fbcb01ac922f8d75bb6910
[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   /**
26    * {@inheritdoc}
27    */
28   public static function defaultSettings() {
29     $options = parent::defaultSettings();
30
31     $options['display_as_link'] = TRUE;
32     return $options;
33   }
34
35   /**
36    * {@inheritdoc}
37    */
38   public function settingsForm(array $form, FormStateInterface $form_state) {
39     $form = parent::settingsForm($form, $form_state);
40
41     $form['display_as_link'] = [
42       '#type' => 'checkbox',
43       '#title' => $this->t('Link to URL'),
44       '#default_value' => $this->getSetting('display_as_link'),
45     ];
46
47     return $form;
48   }
49
50   /**
51    * {@inheritdoc}
52    */
53   public function viewElements(FieldItemListInterface $items, $langcode) {
54     $elements = [];
55
56     if ($items->getEntity()->getEntityTypeId() == 'aggregator_feed') {
57       $url_string = $items->getEntity()->getUrl();
58     }
59     else {
60       $url_string = $items->getEntity()->getLink();
61     }
62
63     foreach ($items as $delta => $item) {
64       if ($this->getSetting('display_as_link') && $url_string) {
65         $elements[$delta] = [
66             '#type' => 'link',
67             '#title' => $item->value,
68             '#url' => Url::fromUri($url_string),
69         ];
70       }
71       else {
72         $elements[$delta] = ['#markup' => $item->value];
73       }
74     }
75
76     return $elements;
77   }
78
79   /**
80    * {@inheritdoc}
81    */
82   public static function isApplicable(FieldDefinitionInterface $field_definition) {
83     return (($field_definition->getTargetEntityTypeId() === 'aggregator_item' || $field_definition->getTargetEntityTypeId() === 'aggregator_feed') && $field_definition->getName() === 'title');
84   }
85
86 }