Создание типа объекта конфигурации в Drupal 8
На этой странице представлен пример того, как создать тип объекта конфигурации со страницами управления администрированием для Drupal 8. Для ознакомления с понятиями простой конфигурации и объектов конфигурации см. Https://drupal.org/node/2120523.
После включения примера модуля, содержащего приведенный ниже код, пример формы конфигурации должен быть доступен в «admin/config/system/example», как показано на скриншоте:

Настройка модуля и входа в меню администратора
example/example.info.yml
name: Example description: 'Manages example configuration.' package: Example type: module core: 8.x
Маршрутизация
(См. некоторые вспомогательные классы, добавленные для работы с путями сущностей, чтобы узнать, как это упростить.)
example/example.routing.yml
Файл routing.yml определяет маршруты для страниц управления: список, добавление, редактирование, удаление.
entity.example.collection:
path: '/admin/config/system/example'
defaults:
_entity_list: 'example'
_title: 'Example configuration'
requirements:
_permission: 'administer site configuration'
entity.example.add_form:
path: '/admin/config/system/example/add'
defaults:
_entity_form: 'example.add'
_title: 'Add example'
requirements:
_permission: 'administer site configuration'
entity.example.edit_form:
path: '/admin/config/system/example/{example}'
defaults:
_entity_form: 'example.edit'
_title: 'Edit example'
requirements:
_permission: 'administer site configuration'
entity.example.delete_form:
path: '/admin/config/system/example/{example}/delete'
defaults:
_entity_form: 'example.delete'
_title: 'Delete example'
requirements:
_permission: 'administer site configuration'
example/example.links.menu.yml
Это добавляет ссылку на страницу конфигурации -> Система
entity.example.collection: title: 'Example' parent: system.admin_config_system description: 'Configure example' route_name: entity.example.collection
example/example.links.action.yml
При этом ссылка «Добавить» появляется на странице списка.
entity.example.add_form:
route_name: 'entity.example.add_form'
title: 'Add example'
appears_on:
- entity.example.collection
Классы типов объектов
example/src/ExampleInterface.php
Предполагая, что у вашей сущности конфигурации есть свойства, вам нужно будет определить некоторые методы set/get на интерфейсе.
namespace Drupal\example;
use Drupal\Core\Config\Entity\ConfigEntityInterface;
/**
* Provides an interface defining an Example entity.
*/
interface ExampleInterface extends ConfigEntityInterface {
// Add get/set methods for your configuration properties here.
}
example/src/Entity/Example.php
Этот файл определяет класс сущности конфигурации.
namespace Drupal\example\Entity;
use Drupal\Core\Config\Entity\ConfigEntityBase;
use Drupal\example\ExampleInterface;
/**
* Defines the Example entity.
*
* @ConfigEntityType(
* id = "example",
* label = @Translation("Example"),
* handlers = {
* "list_builder" = "Drupal\example\Controller\ExampleListBuilder",
* "form" = {
* "add" = "Drupal\example\Form\ExampleForm",
* "edit" = "Drupal\example\Form\ExampleForm",
* "delete" = "Drupal\example\Form\ExampleDeleteForm",
* }
* },
* config_prefix = "example",
* admin_permission = "administer site configuration",
* entity_keys = {
* "id" = "id",
* "label" = "label",
* },
* config_export = {
* "id",
* "label"
* },
* links = {
* "edit-form" = "/admin/config/system/example/{example}",
* "delete-form" = "/admin/config/system/example/{example}/delete",
* }
* )
*/
class Example extends ConfigEntityBase implements ExampleInterface {
/**
* The Example ID.
*
* @var string
*/
public $id;
/**
* The Example label.
*
* @var string
*/
public $label;
// Your specific configuration property get/set methods go here,
// implementing the interface.
}
Ключ admin_permission автоматически разрешает всем пользователям доступ с таким разрешением. Если требуется больше логики, можно указать пользовательский контроллер доступа.
Начиная с Drupal 8.6.x рекомендуется, чтобы все типы объектов конфигурации имели свойство config_export в своих аннотациях (см .: https://www.drupal.org/node/2949023).
Файл схемы конфигурации
example/config/schema/example.schema.yml
example.example.*:
type: config_entity
label: 'Example config'
mapping:
id:
type: string
label: 'ID'
label:
type: label
label: 'Label'
в example.schema.yml добавить свойства/атрибуты, определенные в \Drupal\example\Entity\Example
example.example.* - это переменная конфигурации, которая ссылается на свойства / атрибуты нашего класса, и вы можете указать другое имя переменной для вашей сущности, добавив «config_prefix», например:
@ConfigEntityType( .. ... config_prefix = "variable_name" ...
тогда вы можете сослаться на это следующим образом:
example.variable_name.*: ....
для получения дополнительной информации о схеме конфигурации см. Схема конфигурации/метаданные
Классы сущностей
example/src/Form/ExampleForm.php
namespace Drupal\example\Form;
use Drupal\Core\Entity\EntityForm;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Messenger\MessengerInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
/**
* Form handler for the Example add and edit forms.
*/
class ExampleForm extends EntityForm {
/**
* Constructs an ExampleForm object.
*
* @param \Drupal\Core\Entity\EntityTypeManagerInterface $entityTypeManager
* The entityTypeManager.
*/
public function __construct(EntityTypeManagerInterface $entityTypeManager) {
$this->entityTypeManager = $entityTypeManager;
}
/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container) {
return new static(
$container->get('entity_type.manager')
);
}
/**
* {@inheritdoc}
*/
public function form(array $form, FormStateInterface $form_state) {
$form = parent::form($form, $form_state);
$example = $this->entity;
$form['label'] = [
'#type' => 'textfield',
'#title' => $this->t('Label'),
'#maxlength' => 255,
'#default_value' => $example->label(),
'#description' => $this->t("Label for the Example."),
'#required' => TRUE,
];
$form['id'] = [
'#type' => 'machine_name',
'#default_value' => $example->id(),
'#machine_name' => [
'exists' => [$this, 'exist'],
],
'#disabled' => !$example->isNew(),
];
// You will need additional form elements for your custom properties.
return $form;
}
/**
* {@inheritdoc}
*/
public function save(array $form, FormStateInterface $form_state) {
$example = $this->entity;
$status = $example->save();
if ($status === SAVED_NEW) {
$this->messenger()->addMessage($this->t('The %label Example created.', [
'%label' => $example->label(),
]));
}
else {
$this->messenger()->addMessage($this->t('The %label Example updated.', [
'%label' => $example->label(),
]));
}
$form_state->setRedirect('entity.example.collection');
}
/**
* Helper function to check whether an Example configuration entity exists.
*/
public function exist($id) {
$entity = $this->entityTypeManager->getStorage('example')->getQuery()
->condition('id', $id)
->execute();
return (bool) $entity;
}
}
example/src/Controller/ExampleListBuilder.php
namespace Drupal\example\Controller;
use Drupal\Core\Config\Entity\ConfigEntityListBuilder;
use Drupal\Core\Entity\EntityInterface;
/**
* Provides a listing of Example.
*/
class ExampleListBuilder extends ConfigEntityListBuilder {
/**
* {@inheritdoc}
*/
public function buildHeader() {
$header['label'] = $this->t('Example');
$header['id'] = $this->t('Machine name');
return $header + parent::buildHeader();
}
/**
* {@inheritdoc}
*/
public function buildRow(EntityInterface $entity) {
$row['label'] = $entity->label();
$row['id'] = $entity->id();
// You probably want a few more properties here...
return $row + parent::buildRow($entity);
}
}
example/src/Form/ExampleDeleteForm.php
namespace Drupal\example\Form;
use Drupal\Core\Entity\EntityConfirmFormBase;
use Drupal\Core\Url;
use Drupal\Core\Form\FormStateInterface;
/**
* Builds the form to delete an Example.
*/
class ExampleDeleteForm extends EntityConfirmFormBase {
/**
* {@inheritdoc}
*/
public function getQuestion() {
return $this->t('Are you sure you want to delete %name?', array('%name' => $this->entity->label()));
}
/**
* {@inheritdoc}
*/
public function getCancelUrl() {
return new Url('entity.example.collection');
}
/**
* {@inheritdoc}
*/
public function getConfirmText() {
return $this->t('Delete');
}
/**
* {@inheritdoc}
*/
public function submitForm(array &$form, FormStateInterface $form_state) {
$this->entity->delete();
$this->messenger()->addMessage($this->t('Entity %label has been deleted.', array('%label' => $this->entity->label())));
$form_state->setRedirectUrl($this->getCancelUrl());
}
}