View source
<?php
namespace Drupal\yamlform\Plugin\Field\FieldFormatter;
use Drupal\Core\Field\FieldDefinitionInterface;
use Drupal\Core\Field\FieldItemListInterface;
use Drupal\Core\Field\Plugin\Field\FieldFormatter\EntityReferenceFormatterBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
use Drupal\Core\Utility\Token;
use Drupal\yamlform\YamlFormMessageManagerInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
class YamlFormEntityReferenceLinkFormatter extends EntityReferenceFormatterBase implements ContainerFactoryPluginInterface {
protected $messageManager;
protected $token;
public function __construct($plugin_id, $plugin_definition, FieldDefinitionInterface $field_definition, array $settings, $label, $view_mode, array $third_party_settings, YamlFormMessageManagerInterface $message_manager, Token $token) {
parent::__construct($plugin_id, $plugin_definition, $field_definition, $settings, $label, $view_mode, $third_party_settings);
$this->messageManager = $message_manager;
$this->token = $token;
}
public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
return new static($plugin_id, $plugin_definition, $configuration['field_definition'], $configuration['settings'], $configuration['label'], $configuration['view_mode'], $configuration['third_party_settings'], $container
->get('yamlform.message_manager'), $container
->get('token'));
}
public static function defaultSettings() {
return [
'label' => 'Go to [yamlform:title] form',
] + parent::defaultSettings();
}
public function settingsSummary() {
$summary = [];
$summary[] = $this
->t('Label: @label', [
'@label' => $this
->getSetting('label'),
]);
return $summary;
}
public function settingsForm(array $form, FormStateInterface $form_state) {
$element['label'] = [
'#title' => $this
->t('Label'),
'#type' => 'textfield',
'#default_value' => $this
->getSetting('label'),
'#required' => TRUE,
];
return $element;
}
public function viewElements(FieldItemListInterface $items, $langcode) {
$source_entity = $items
->getEntity();
$this->messageManager
->setSourceEntity($source_entity);
$elements = [];
foreach ($this
->getEntitiesToView($items, $langcode) as $delta => $entity) {
if ($entity
->id() && $items[$delta]->status) {
$link_options = [
'query' => [
'source_entity_type' => $source_entity
->getEntityTypeId(),
'source_entity_id' => $source_entity
->id(),
],
];
$elements[$delta] = [
'#type' => 'link',
'#title' => $this->token
->replace($this
->getSetting('label'), [
'yamlform' => $entity,
]),
'#url' => $entity
->toUrl('canonical', $link_options),
];
}
else {
$this->messageManager
->setYamlForm($entity);
$elements[$delta] = $this->messageManager
->build(YamlFormMessageManagerInterface::FORM_CLOSED_MESSAGE);
}
}
return $elements;
}
}