I have a custom field. The FieldType plugin provides a settings form that adds a field to the form. The field is a group of checkboxes...think the paragraph types selection when adding a entity revisions field to a content type.
The form displays correctly. Two of the checkboxes are checked by default correctly. But the values don't get saved.
I've put a breakpoint where the settings are retrieved:
$def = $items->getFieldDefinition();
return $def->getSetting('allowed_schemes') ?? UrlItem::getSchemes();
which returns null, as does $def->getSettings(). I've also put a breakpoint in FieldItemBase where it retrieves the settings...also null.
It might have something to do with the schema method. I haven't figured out yet what I need to put there.
Here is my plugin.
<?php
namespace Drupal\url_text\Plugin\Field\FieldType;
use Drupal\Core\Field\FieldDefinitionInterface;
use Drupal\Core\Field\FieldItemBase;
use Drupal\Core\Field\FieldStorageDefinitionInterface;
use Drupal\Core\Form\FormStateInterface;
/**
* Defines the 'url' entity field type.
*
* @FieldType(
* id = "url",
* label = @Translation("URL"),
* description = @Translation("A field containing a plain string URL value."),
* category = @Translation("General"),
* default_widget = "url_textfield",
* default_formatter = "url"
* )
*/
class UrlItem extends FieldItemBase {
/**
* {@inheritdoc}
*/
public static function schema(FieldStorageDefinitionInterface $field_definition): array {
return [
'columns' => [
'value' => [
'type' => $field_definition->getSetting('is_ascii') === TRUE ? 'varchar_ascii' : 'varchar',
'length' => (int) $field_definition->getSetting('max_length'),
'binary' => $field_definition->getSetting('case_sensitive'),
],
],
];
}
/**
* {@inheritdoc}
*/
public function isEmpty(): bool {
$value = $this->getValue();
return empty($value['value']);
}
/**
* {@inheritdoc}
*/
public static function propertyDefinitions(FieldStorageDefinitionInterface $field_definition): array {
return [];
}
/**
* {@inheritdoc}
*/
public function fieldSettingsForm(array $form, FormStateInterface $form_state): array {
$settings = $this->getSettings();
$element['allowed_schemes'] = [
'#type' => 'checkboxes',
'#title' => $this->t('Allowed Schemes'),
'#options' => $this->getSchemes(),
'#default_value' => $settings['allowed_schemes'] ?? ['http', 'https'],
'#description' => $this->t('Allowed URL schemes for the URL. If none are selected, then all are allowed.'),
];
return $element;
}
/**
* Provide an array of URL schemes to allow.
*/
public static function getSchemes(): array {
return [
'http' => 'http://',
'https' => 'https://',
'ftp' => 'ftp://',
'mailto' => 'mailto://',
'sftp' => 'sftp://',
'ssh' => 'ssh://',
'tel' => 'tel://',
];
}
}