EditableFieldsHelper.php in Editable Fields 8
File
src/services/EditableFieldsHelper.php
View source
<?php
namespace Drupal\editablefields\services;
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Field\FieldTypePluginManagerInterface;
use Drupal\Core\Form\FormBuilderInterface;
use Drupal\Core\DependencyInjection\ClassResolverInterface;
use Drupal\Core\Session\AccountProxyInterface;
use Drupal\Core\Entity\EntityDisplayRepositoryInterface;
class EditableFieldsHelper implements EditableFieldsHelperInterface {
protected $pluginManagerFieldFieldType;
protected $formBuilder;
protected $classResolver;
protected $currentUser;
protected $entityDisplayRepository;
public function __construct(FieldTypePluginManagerInterface $plugin_manager_field_field_type, FormBuilderInterface $form_builder, ClassResolverInterface $class_resolver, AccountProxyInterface $current_user, EntityDisplayRepositoryInterface $entity_display_repository) {
$this->pluginManagerFieldFieldType = $plugin_manager_field_field_type;
$this->formBuilder = $form_builder;
$this->classResolver = $class_resolver;
$this->currentUser = $current_user;
$this->entityDisplayRepository = $entity_display_repository;
}
public function formatterInfoAlter(array &$info) {
if (empty($info[self::FORMATTER_ID])) {
return;
}
$info[self::FORMATTER_ID]['field_types'] = $this
->getAllFieldTypes();
}
public function getAllFieldTypes() {
return array_keys($this->pluginManagerFieldFieldType
->getDefinitions());
}
public function checkAccess(EntityInterface $entity) {
$can_edit = $entity
->access('edit');
$can_use = $this->currentUser
->hasPermission(self::PERMISSION);
return $can_edit && $can_use;
}
public function isAdmin() {
return $this->currentUser
->hasPermission(self::ADMIN_PERMISSION);
}
public function getForm(EntityInterface $entity, string $field_name, string $form_mode) {
$form_object = $this->classResolver
->getInstanceFromDefinition(self::FORM_CLASS);
$form_object
->setDefaults($entity, $field_name, $form_mode);
return $this->formBuilder
->getForm($form_object);
}
public function getFormDisplay(EntityInterface $entity, $form_mode) {
return $this->entityDisplayRepository
->getFormDisplay($entity
->getEntityTypeId(), $entity
->bundle(), $form_mode);
}
public function getModesOptions() {
$options[self::DEFAULT_FORM_MODE] = self::DEFAULT_FORM_MODE;
$form_modes = $this->entityDisplayRepository
->getAllFormModes();
foreach ($form_modes as $entity_type => $modes) {
foreach ($modes as $mode) {
$label = explode('.', $mode['id']);
$label = end($label);
$options[$entity_type][$label] = $label;
}
}
return $options;
}
}