I'm defining a new custom Field Type in Drupal 8, let's say MyFieldType
, with custom widget and formatter also.
Such Field Type should have these two fields:
text
: a simple text valueimage
: a field where the user that use this Field Type can upload an image, as the built-in image field type.
I created the custom field type with the text
field with no problems. Now I'm trying to add the image
field also, but I'm stuck and I don't understand how to proceed.
What is the correct way to add an image upload field in a custom Field Type?
What I tried
Below there are the main parts from the custom Field Type. All files are from the folder modules\custom\my_field_type\src\Plugin\Field
.
From the file FieldType\MyFieldType.php
:
class MyFieldType extends FieldItemBase {
//
public static function propertyDefinitions(
FieldStorageDefinitionInterface $field_definition
) {
$properties['text'] = DataDefinition::create('string')
->setLabel(t('Text Value'));
// $properties['image'] ... go here?
// ...
return $properties;
}
//
public static function schema(
FieldStorageDefinitionInterface $field_definition
) {
$columns = array(
'text' => array(
'type' => 'varchar',
'length' => 255,
),
// What column for the 'image' field?
// ...
);
$schema = array(
'columns' => $columns,
);
return $schema;
}
}
From the file FieldWidget\MyFieldTypeWidget.php
:
class MyFieldTypeWidget extends WidgetBase {
public function formElement(
FieldItemListInterface $items,
$delta,
Array $element,
Array &$form,
FormStateInterface $formState
) {
$element['value'] = [
'#type' => 'textfield',
'#title' => t('Value'),
'#default_value' => isset($items[$delta]->value) ?
$items[$delta]->value : null,
'#empty_value' => '',
];
$element['image'] = [
'#type' => 'file',
'#title' => t('Image'),
'#default_value' => isset($items[$delta]->image) ?
$items[$delta]->image : null,
'#empty_value' => '',
];
return $element;
}
}
I can see the file upload field in the edit form (adding a new field with this custom type), but I don't know how to go on and (eventually) how to handle the uploaded image inside the class MyFieldType
.