function FileItem::generateSampleValue

Same name in other branches
  1. 9 core/modules/file/src/Plugin/Field/FieldType/FileItem.php \Drupal\file\Plugin\Field\FieldType\FileItem::generateSampleValue()
  2. 8.9.x core/modules/file/src/Plugin/Field/FieldType/FileItem.php \Drupal\file\Plugin\Field\FieldType\FileItem::generateSampleValue()
  3. 11.x core/modules/file/src/Plugin/Field/FieldType/FileItem.php \Drupal\file\Plugin\Field\FieldType\FileItem::generateSampleValue()

Overrides EntityReferenceItem::generateSampleValue

1 method overrides FileItem::generateSampleValue()
ImageItem::generateSampleValue in core/modules/image/src/Plugin/Field/FieldType/ImageItem.php

File

core/modules/file/src/Plugin/Field/FieldType/FileItem.php, line 354

Class

FileItem
Plugin implementation of the 'file' field type.

Namespace

Drupal\file\Plugin\Field\FieldType

Code

public static function generateSampleValue(FieldDefinitionInterface $field_definition) {
    $random = new Random();
    $settings = $field_definition->getSettings();
    // Prepare destination.
    $dirname = static::doGetUploadLocation($settings);
    \Drupal::service('file_system')->prepareDirectory($dirname, FileSystemInterface::CREATE_DIRECTORY);
    // Generate a file entity.
    $destination = $dirname . '/' . $random->name(10, TRUE) . '.txt';
    $data = $random->paragraphs(3);
    
    /** @var \Drupal\file\FileRepositoryInterface $file_repository */
    $file_repository = \Drupal::service('file.repository');
    $file = $file_repository->writeData($data, $destination, FileExists::Error);
    $values = [
        'target_id' => $file->id(),
        'display' => (int) $settings['display_default'],
        'description' => $random->sentences(10),
    ];
    return $values;
}

Buggy or inaccurate documentation? Please file an issue. Need support? Need help programming? Connect with the Drupal community.