Skip to content
Snippets Groups Projects

Draft: Series per Entity per Entity Reference

4 files
+ 131
0
Compare changes
  • Side-by-side
  • Inline
Files
4
<?php
namespace Drupal\serialper\Plugin\Field\FieldType;
use Drupal\serial\Plugin\Field\FieldType\SerialItem;
use Drupal\Core\Field\FieldStorageDefinitionInterface;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\TypedData\DataDefinition;
use Drupal\Core\TypedData\TranslatableInterface;
/**
* Plugin implementation of the 'serialper' field type.
*
* @todo should not be translatable, by default
*
* @FieldType(
* id = "serialper",
* label = @Translation("Serial per Entity Reference"),
* description = @Translation("Auto increment per referenced entity serial field type."),
* category = "number",
* default_widget = "serial_default_widget",
* default_formatter = "serial_default_formatter"
* )
*/
class SerialPerEntityReferenceItem extends SerialItem {
/**
* {@inheritdoc}
*/
public static function defaultStorageSettings() {
return [
'reference_field' => '',
] + parent::defaultStorageSettings();
}
/**
* {@inheritdoc}
*/
public function storageSettingsForm(array &$form, FormStateInterface $form_state, $has_data) {
$element = [];
$options = [];
$fields = $this->getEntity()->getFields() ?? [];
foreach ($fields as $field_name => $field_info) {
/** @var Drupal\Core\Field\EntityReferenceFieldItemList $field_info */
// Cannot use ->get('field_type') as it only works on non-base fields.
$field_definition = $field_info->getDataDefinition();
$field_type = $field_definition->getType() ?? '';
if ($field_type === 'entity_reference') {
if (method_exists($field_definition, 'label')) {
// If there was no label, it's probably a whack entity reference field
// that we cannot use anyway, i don't understand why content type,
// revision_uid, uid, and menu_link base fields claim the entity
// reference mantel and then drop the ball on something so basic.
$options[$field_name] = $field_definition->label();
}
}
}
$element['reference_field'] = [
'#type' => 'select',
'#title' => $this->t('Reference field'),
'#description' => $this->t('The field that contains the entity reference which will determine when this field starts a new series.'),
'#default_value' => $this->getSetting('reference_field'),
'#options' => $options,
'#required' => TRUE,
'#disabled' => $has_data,
];
return $element + parent::storageSettingsForm($form, $form_state, $has_data);
}
/**
* {@inheritdoc}
*/
public function preSave() {
/** @var \Drupal\serial\SerialStorageInterface $serialStorage */
$serialStorage = \Drupal::getContainer()->get('serial.sql_storage');
$storageName = $serialStorage->createStorageNameFromField($this->getFieldDefinition(), $this->getEntity());
// Create table if it does not exist already.
if (!\Drupal::database()->schema()->tableExists($storageName)) {
$serialStorage->createStorageFromName($storageName);
}
parent::preSave();
}
}
Loading