View source
<?php
namespace Drupal\contact_formatter\Plugin\Field\FieldFormatter;
use Drupal\Core\Field\FieldItemListInterface;
use Drupal\Core\Field\FormatterBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Field\FieldDefinitionInterface;
use Drupal\Core\Session\AccountInterface;
use Drupal\Core\Render\RendererInterface;
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
class ContactFieldFormatter extends FormatterBase implements ContainerFactoryPluginInterface {
protected $renderer;
public function __construct($plugin_id, $plugin_definition, FieldDefinitionInterface $field_definition, array $settings, $label, $view_mode, array $third_party_settings, AccountInterface $current_user, RendererInterface $renderer) {
parent::__construct($plugin_id, $plugin_definition, $field_definition, $settings, $label, $view_mode, $third_party_settings);
$this->renderer = $renderer;
}
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('current_user'), $container
->get('renderer'));
}
public static function defaultSettings() {
return [] + parent::defaultSettings();
}
public function settingsForm(array $form, FormStateInterface $form_state) {
return [] + parent::settingsForm($form, $form_state);
}
public function settingsSummary() {
$summary = [];
return $summary;
}
public function viewElements(FieldItemListInterface $items, $langcode) {
$elements = [];
foreach ($items as $delta => $item) {
$message = \Drupal::entityTypeManager()
->getStorage('contact_message')
->create([
'contact_form' => $item
->getValue()['target_id'],
]);
if (!$message
->isPersonal()) {
$form = \Drupal::service('entity.form_builder')
->getForm($message);
$elements[$delta] = [
'#markup' => $this->renderer
->render($form),
];
}
}
return $elements;
}
}