I have been breaking my head on this issue for a few days now. Using Drupal 9.2.x, I am building a custom field module for a client that has multiple fields. I isolated the problem by only including a managed file field for now, because the other fields are not causing this issue.

I defined a managed file element in my Widget class, which extends WidgetBase:

public function formElement(FieldItemListInterface $items, $delta, array $element, array &$form, FormStateInterface $form_state) {

    $element['target_id'] = [
      '#type' => 'managed_file',
      '#title' => $this->t('Right image'),
      '#upload_location' => 'public://disco-field-images/',
      '#upload_validators' => array(
        'file_validate_extensions' => array('gif png jpg jpeg')
      '#default_value' => array($items[$delta]->target_id),

    return $element;


I defined my schema as follows in my Item class:

 public static function schema(FieldStorageDefinitionInterface $field_definition) {
return [
  'columns' => [
    'target_id' => [
      'description' => 'The ID of the file entity',
      'type' => 'int',
      'unsigned' => TRUE,
  'indexes' => [
    'target_id' => ['target_id'],
  'foreign keys' => [
    'target_id' => [
      'table' => 'file_managed',
      'columns' => ['target_id' => 'fid'],


And finally, I have added a property defintion for the field:

public static function propertyDefinitions(FieldStorageDefinitionInterface $field_definition) {

$properties['target_id'] = ListDataDefinition::create('integer')
  ->setLabel(t('target ID'))

 return $properties;


Somehow this results in the file being uploaded into the managed files table, getting a fid and all looks well from there. However, the field table (node__fieldname) which contains the referencing target_id to the file_managed table somehow always defaults to 1. So no reference is being made to the uploaded file. I have tried working with other property definitions:

    $properties['target_id'] = DataDefinition::create('integer')
  ->setLabel(t('target ID'));


$properties['target_id'] = DataReferenceTargetDefinition::create('integer')
 ->setLabel('Foreign key referencing managed file')
 ->setSetting('unsigned', TRUE)

But no luck there. It seems a bit weird to me though, that the database target id needs to be integer and the file upload widget works with an array. Thats why I am aiming at the property definitions/schema as a cause here. If I try to work with a single int property value:


I get a primitive type error because the managed file element expects an array. Any suggestions? Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.