Een configuratieobjecttype aanmaken in Drupal 8
Op deze pagina wordt een voorbeeld gegeven van hoe je een configuratieobjecttype kunt maken met beheerderspagina’s in Drupal 8. Voor een inleiding tot de concepten van eenvoudige configuratie en configuratieobjecten, zie https://drupal.org/node/2120523.
Na het inschakelen van de voorbeeldmodule met onderstaande code, zou het voorbeeldconfiguratieformulier beschikbaar moeten zijn op “admin/config/system/example”, zoals getoond op de screenshot:

Module-instelling en admin menu-invoer
example/example.info.yml
name: Example description: 'Beheert voorbeeldconfiguratie.' package: Example type: module core: 8.x
Routing
(Zie hulpmiddelen die zijn toegevoegd voor het werken met entiteitspaden om te leren hoe dit eenvoudiger kan worden gemaakt.)
example/example.routing.yml
Het bestand routing.yml definieert routes voor de beheerpagina’s: lijst, toevoegen, bewerken, verwijderen.
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
Dit voegt een link toe in Configuratie -> Systeem
entity.example.collection: title: 'Example' parent: system.admin_config_system description: 'Configure example' route_name: entity.example.collection
example/example.links.action.yml
Hiermee verschijnt de link “Toevoegen” op de lijstpagina.
entity.example.add_form:
route_name: 'entity.example.add_form'
title: 'Add example'
appears_on:
- entity.example.collection
Objecttype-klassen
example/src/ExampleInterface.php
Aangenomen dat uw configuratie-entiteit eigenschappen heeft, moet u enkele set/get-methoden definiëren in de interface.
namespace Drupal\example;
use Drupal\Core\Config\Entity\ConfigEntityInterface;
/**
* Biedt een interface die een Example-entiteit definieert.
*/
interface ExampleInterface extends ConfigEntityInterface {
// Voeg hier get/set-methoden toe voor uw configuratie-eigenschappen.
}
example/src/Entity/Example.php
Dit bestand definieert de configuratie-entiteitsklasse.
namespace Drupal\example\Entity;
use Drupal\Core\Config\Entity\ConfigEntityBase;
use Drupal\example\ExampleInterface;
/**
* Definieert de Example-entiteit.
*
* @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 {
/**
* Het Example ID.
*
* @var string
*/
public $id;
/**
* Het Example label.
*
* @var string
*/
public $label;
// Voeg hier de specifieke configuratieproperty get/set-methoden toe,
// ter implementatie van de interface.
}
De sleutel admin_permission geeft automatisch toegang aan alle gebruikers met die permissie. Indien meer logica nodig is, kan een aangepaste access controller worden opgegeven.
Vanaf Drupal 8.6.x wordt aanbevolen dat alle configuratieobjecttypes de eigenschap config_export in hun annotaties hebben (zie: https://www.drupal.org/node/2949023).
Configuratieschema-bestand
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'
In example.schema.yml voegt u de eigenschappen/attributen toe die zijn gedefinieerd in \Drupal\example\Entity\Example
example.example.* is een configuratievariabele die verwijst naar de eigenschappen/attributen van onze klasse, en u kunt een andere variabelenaam voor uw entiteit specificeren door “config_prefix” toe te voegen, bijvoorbeeld:
@ConfigEntityType( .. ... config_prefix = "variable_name" ...
dan kunt u er als volgt naar verwijzen:
example.variable_name.*: ....
voor meer informatie over configuratieschema’s, zie Configuratieschema/metadata
Entiteitsklassen
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 voor de Example toevoegen- en bewerken-formulieren.
*/
class ExampleForm extends EntityForm {
/**
* Maakt een ExampleForm-object.
*
* @param \Drupal\Core\Entity\EntityTypeManagerInterface $entityTypeManager
* De 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 voor de Example."),
'#required' => TRUE,
];
$form['id'] = [
'#type' => 'machine_name',
'#default_value' => $example->id(),
'#machine_name' => [
'exists' => [$this, 'exist'],
],
'#disabled' => !$example->isNew(),
];
// Voeg extra formelementen toe voor uw eigen 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('De %label Example is aangemaakt.', [
'%label' => $example->label(),
]));
}
else {
$this->messenger()->addMessage($this->t('De %label Example is bijgewerkt.', [
'%label' => $example->label(),
]));
}
$form_state->setRedirect('entity.example.collection');
}
/**
* Helperfunctie om te controleren of een Example configuratie-entiteit bestaat.
*/
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;
/**
* Biedt een lijst van 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();
// U wilt hier waarschijnlijk nog meer properties weergeven...
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;
/**
* Bouwt het formulier om een Example te verwijderen.
*/
class ExampleDeleteForm extends EntityConfirmFormBase {
/**
* {@inheritdoc}
*/
public function getQuestion() {
return $this->t('Weet u zeker dat u %name wilt verwijderen?', 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('Entiteit %label is verwijderd.', array('%label' => $this->entity->label())));
$form_state->setRedirectUrl($this->getCancelUrl());
}
}