本文整理汇总了PHP中Drupal\file\Entity\File::load方法的典型用法代码示例。如果您正苦于以下问题:PHP File::load方法的具体用法?PHP File::load怎么用?PHP File::load使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类Drupal\file\Entity\File
的用法示例。
在下文中一共展示了File::load方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。
示例1: testInUse
/**
* Tries deleting a file that is in use.
*/
function testInUse()
{
$file = $this->createFile();
$file_usage = $this->container->get('file.usage');
$file_usage->add($file, 'testing', 'test', 1);
$file_usage->add($file, 'testing', 'test', 1);
$file_usage->delete($file, 'testing', 'test', 1);
$usage = $file_usage->listUsage($file);
$this->assertEqual($usage['testing']['test'], array(1 => 1), 'Test file is still in use.');
$this->assertTrue(file_exists($file->getFileUri()), 'File still exists on the disk.');
$this->assertTrue(File::load($file->id()), 'File still exists in the database.');
// Clear out the call to hook_file_load().
file_test_reset();
$file_usage->delete($file, 'testing', 'test', 1);
$usage = $file_usage->listUsage($file);
$this->assertFileHooksCalled(array('load', 'update'));
$this->assertTrue(empty($usage), 'File usage data was removed.');
$this->assertTrue(file_exists($file->getFileUri()), 'File still exists on the disk.');
$file = File::load($file->id());
$this->assertTrue($file, 'File still exists in the database.');
$this->assertTrue($file->isTemporary(), 'File is temporary.');
file_test_reset();
// Call file_cron() to clean up the file. Make sure the changed timestamp
// of the file is older than the system.file.temporary_maximum_age
// configuration value.
db_update('file_managed')->fields(array('changed' => REQUEST_TIME - ($this->config('system.file')->get('temporary_maximum_age') + 1)))->condition('fid', $file->id())->execute();
\Drupal::service('cron')->run();
// file_cron() loads
$this->assertFileHooksCalled(array('delete'));
$this->assertFalse(file_exists($file->getFileUri()), 'File has been deleted after its last usage was removed.');
$this->assertFalse(File::load($file->id()), 'File was removed from the database.');
}
示例2: buildForm
/**
* {@inheritdoc}
*/
public function buildForm(array $form, FormStateInterface $form_state, $grouping = NULL)
{
// Load logo image.
$rendered_image = NULL;
if (!empty($grouping->logo_fid)) {
$file = File::load($grouping->logo_fid);
if ($file) {
$logo_url = ImageStyle::load('ea_groupings_200x200')->buildUrl($file->getFileUri());
$image_array = array('#theme' => 'image', '#uri' => $logo_url, '#alt' => $this->t('Logo for @grouping', array('@grouping' => $grouping->title)), '#title' => $this->t('@grouping', array('@grouping' => $grouping->title)));
$rendered_image = \Drupal::service('renderer')->render($image_array);
}
}
// Construct form.
$form = array();
$form['gid'] = array('#type' => 'value', '#value' => $grouping->gid);
$form['add'] = array('#type' => 'fieldset', '#description' => $this->t('Update grouping'), '#title' => $this->t('Edit grouping'));
$form['add']['title'] = array('#type' => 'textfield', '#title' => $this->t('Title'), '#description' => $this->t('Title of grouping'), '#size' => 20, '#maxlength' => 20, '#required' => FALSE, '#default_value' => $grouping->title);
$form['add']['description'] = array('#type' => 'textarea', '#title' => $this->t('Description'), '#description' => $this->t('A short description of the grouping'), '#required' => FALSE, '#default_value' => $grouping->description);
$form['add']['logo'] = array('#type' => 'markup', '#markup' => $rendered_image);
$form['add']['logo_fid'] = array('#title' => $this->t('Update logo'), '#type' => 'managed_file', '#description' => $this->t('Upload a logo for the grouping'), '#default_value' => NULL, '#upload_location' => 'public://logos/');
$form['add']['time_zone'] = array('#title' => $this->t('Timezone'), '#type' => 'select', '#description' => $this->t('Select a time zone for the grouping'), '#options' => _ea_groupings_get_time_zones(), '#default_value' => $grouping->time_zone);
$form['add']['parent_gid'] = array('#type' => 'select', '#description' => $this->t('Select a parent grouping'), '#options' => _ea_groupings_get_groupings_list(FALSE, $grouping->gid), '#disabled' => _ea_groupings_is_parent($grouping->gid), '#default_value' => $grouping->parent_gid);
$form['add']['submit'] = array('#type' => 'submit', '#name' => 'add_group', '#value' => $this->t('Update grouping'), '#weight' => 100);
$form['add']['old_title'] = array('#type' => 'value', '#value' => $grouping->title);
$form['add']['old_logo_fid'] = array('#type' => 'value', '#value' => $grouping->logo_fid);
$form['add']['old_parent_gid'] = array('#type' => 'value', '#value' => $grouping->parent_gid);
return $form;
}
示例3: submitForm
/**
* {@inheritdoc}
*/
public function submitForm(array &$form, FormStateInterface $form_state)
{
// Pass the file to the parser.
$fid = $form_state->getValue('mtg_import_json_file');
$fid = reset($fid);
if ($fid == 0) {
return FALSE;
}
$file = File::load($fid);
if (!$file) {
drupal_set_message('Unable to load file.');
\Drupal::logger('mtg_import')->error(t('Unable to load the file.'));
return FALSE;
}
$uri = $file->uri->value;
$file_contents_raw = file_get_contents($uri);
$file_contents = json_decode($file_contents_raw);
if (!empty($file_contents->cards)) {
$operations = [['mtg_import_parse_set_data', [$file_contents]]];
$chunks = array_chunk($file_contents->cards, 20);
foreach ($chunks as $chunk) {
$operations[] = ['mtg_import_parse_card_data', [$chunk]];
}
$batch = ['title' => t('Importing'), 'operations' => $operations, 'finished' => 'mtg_import_completed', 'progress_message' => t('Completed part @current of @total.')];
batch_set($batch);
} else {
drupal_set_message(t('There are no cards in the file, so no import will take place.'), 'warning');
}
}
示例4: submitForm
/**
* {@inheritdoc}
*/
public function submitForm(array &$form, FormStateInterface $form_state)
{
$values = $form_state->getValues();
$file = File::load($values['file'][0]);
// Load File entity.
$read_file = new \SplFileObject($file->url());
// Create file handler.
$lines = 1;
$in_queue = 0;
$queue = \Drupal::queue('eventninja');
// Load queue
while (!$read_file->eof()) {
$data = $read_file->fgetcsv(';');
if ($lines > 1) {
// skip headers
$user = user_load_by_mail($data[1]);
if ($user === false) {
// Verify if user with specified email does not exist.
$queue->createItem($data);
$in_queue++;
} else {
$this->logger('eventninja')->log(RfcLogLevel::NOTICE, 'User {mail} hasn\'t been created.', ['mail' => $data[1]]);
}
}
$lines++;
}
if ($lines > 1) {
drupal_set_message($this->t('@num records was scheduled for import', array('@num' => $in_queue)), 'success');
} else {
drupal_set_message($this->t('File contains only headers'), 'error');
}
}
示例5: testFiles
/**
* Tests the Drupal 6 files to Drupal 8 migration.
*/
public function testFiles()
{
/** @var \Drupal\file\FileInterface $file */
$file = File::load(1);
$this->assertIdentical('Image1.png', $file->getFilename());
$this->assertIdentical('39325', $file->getSize());
$this->assertIdentical('public://image-1.png', $file->getFileUri());
$this->assertIdentical('image/png', $file->getMimeType());
$this->assertIdentical("1", $file->getOwnerId());
// It is pointless to run the second half from MigrateDrupal6Test.
if (empty($this->standalone)) {
return;
}
// Test that we can re-import and also test with file_directory_path set.
db_truncate(entity_load('migration', 'd6_file')->getIdMap()->mapTableName())->execute();
// Update the file_directory_path.
Database::getConnection('default', 'migrate')->update('variable')->fields(array('value' => serialize('files/test')))->condition('name', 'file_directory_path')->execute();
Database::getConnection('default', 'migrate')->update('variable')->fields(array('value' => serialize($this->getTempFilesDirectory())))->condition('name', 'file_directory_temp')->execute();
$migration = entity_load_unchanged('migration', 'd6_file');
$this->executeMigration($migration);
$file = File::load(2);
$this->assertIdentical('public://core/modules/simpletest/files/image-2.jpg', $file->getFileUri());
// Ensure that a temporary file has been migrated.
$file = File::load(6);
$this->assertIdentical('temporary://' . static::getUniqueFilename(), $file->getFileUri());
}
示例6: content
public function content($nid) {
$node = \Drupal::entityManager()->getStorage('node')->load($nid);
$fields = $node->getFieldDefinitions();
$fcArray = [];
foreach ($fields as $field){
$type = $field->getType();
if ($type == 'field_collection') {
$field_collection = $field->get('field_name');
foreach ($node->$field_collection as $key => $item){
$item = $item->value;
// $fcArray[$key];
$fc = FieldCollectionItem::load($item);
foreach ($fc as $fckey => $field){
$fcArray[$key][$fckey] = $field->value;
if (is_object($field[0]) && $field[0]->height){
$image = File::load($field[0]->target_id);
$fcArray[$key][$fckey] = str_replace('public://', '/drupal/sites/default/files/', $image->uri->value);
$fcArray[$key]['field_mosaic_image_alt'] = $field[0]->alt;
}
if (is_object($field[0]) && $field[0]->uri){
$fcArray[$key][$fckey] = str_replace('internal:', '', $field[0]->uri);
}
}
}
}
}
return new JsonResponse($fcArray);
}
示例7: testEmbedButtonIconUsage
/**
* Tests the embed_button and file usage integration.
*/
public function testEmbedButtonIconUsage()
{
$this->enableModules(['system', 'user', 'file']);
$this->installSchema('file', ['file_usage']);
$this->installConfig(['system']);
$this->installEntitySchema('user');
$this->installEntitySchema('file');
$this->installEntitySchema('embed_button');
$file1 = file_save_data(file_get_contents('core/misc/druplicon.png'));
$file1->setTemporary();
$file1->save();
$file2 = file_save_data(file_get_contents('core/misc/druplicon.png'));
$file2->setTemporary();
$file2->save();
$button = array('id' => 'test_button', 'label' => 'Testing embed button instance', 'type_id' => 'embed_test_default', 'icon_uuid' => $file1->uuid());
$entity = EmbedButton::create($button);
$entity->save();
$this->assertTrue(File::load($file1->id())->isPermanent());
// Delete the icon from the button.
$entity->icon_uuid = NULL;
$entity->save();
$this->assertTrue(File::load($file1->id())->isTemporary());
$entity->icon_uuid = $file1->uuid();
$entity->save();
$this->assertTrue(File::load($file1->id())->isPermanent());
$entity->icon_uuid = $file2->uuid();
$entity->save();
$this->assertTrue(File::load($file1->id())->isTemporary());
$this->assertTrue(File::load($file2->id())->isPermanent());
$entity->delete();
$this->assertTrue(File::load($file2->id())->isTemporary());
}
示例8: testFileFieldRSSContent
/**
* Tests RSS enclosure formatter display for RSS feeds.
*/
function testFileFieldRSSContent()
{
$node_storage = $this->container->get('entity.manager')->getStorage('node');
$field_name = strtolower($this->randomMachineName());
$type_name = 'article';
$this->createFileField($field_name, 'node', $type_name);
// RSS display must be added manually.
$this->drupalGet("admin/structure/types/manage/{$type_name}/display");
$edit = array("display_modes_custom[rss]" => '1');
$this->drupalPostForm(NULL, $edit, t('Save'));
// Change the format to 'RSS enclosure'.
$this->drupalGet("admin/structure/types/manage/{$type_name}/display/rss");
$edit = array("fields[{$field_name}][type]" => 'file_rss_enclosure');
$this->drupalPostForm(NULL, $edit, t('Save'));
// Create a new node with a file field set. Promote to frontpage
// needs to be set so this node will appear in the RSS feed.
$node = $this->drupalCreateNode(array('type' => $type_name, 'promote' => 1));
$test_file = $this->getTestFile('text');
// Create a new node with the uploaded file.
$nid = $this->uploadNodeFile($test_file, $field_name, $node->id());
// Get the uploaded file from the node.
$node_storage->resetCache(array($nid));
$node = $node_storage->load($nid);
$node_file = File::load($node->{$field_name}->target_id);
// Check that the RSS enclosure appears in the RSS feed.
$this->drupalGet('rss.xml');
$uploaded_filename = str_replace('public://', '', $node_file->getFileUri());
$test_element = sprintf('<enclosure url="%s" length="%s" type="%s" />', file_create_url("public://{$uploaded_filename}", array('absolute' => TRUE)), $node_file->getSize(), $node_file->getMimeType());
$this->assertRaw($test_element, 'File field RSS enclosure is displayed when viewing the RSS feed.');
}
示例9: submitForm
/**
* {@inheritdoc}
*/
public function submitForm(array &$form, FormStateInterface $form_state)
{
drupal_set_message('Settings saved');
// Fetch the file id previously saved.
$config = $this->config('cfia_base.settings');
$old_fid = $config->get('cfia_frontpage.frontpage_image', '');
// Load the file set in the form.
$value = $form_state->getValue('frontpage_image');
$form_fid = count($value) > 0 ? $value[0] : 0;
$file = $form_fid ? File::load($form_fid) : FALSE;
// If a file is set.
if ($file) {
$fid = $file->id();
// Check if the file has changed.
if ($fid != $old_fid) {
// Remove old file.
if ($old_fid) {
removeFile($old_fid);
}
// Add file to file_usage table.
\Drupal::service('file.usage')->add($file, 'cfia_base', 'user', '1');
}
} else {
// If old file exists but no file set in form, remove old file.
if ($old_fid) {
removeFile($old_fid);
}
}
$this->configFactory()->getEditable('cfia_base.settings')->set('cfia_frontpage.frontpage_title', $form_state->getValue('frontpage_title'))->set('cfia_frontpage.frontpage_lead', $form_state->getValue('frontpage_lead'))->set('cfia_frontpage.frontpage_sub', $form_state->getValue('frontpage_sub'))->set('cfia_frontpage.frontpage_button', $form_state->getValue('frontpage_button'))->set('cfia_frontpage.frontpage_link', $form_state->getValue('frontpage_link'))->set('cfia_footer.footer_text', $form_state->getValue('footer_text')['value'])->set('cfia_footer.footer_twitter', $form_state->getValue('footer_twitter'))->set('cfia_footer.footer_instagram', $form_state->getValue('footer_instagram'))->set('cfia_footer.footer_linkedin', $form_state->getValue('footer_linkedin'))->set('cfia_frontpage.frontpage_image', $file ? $file->id() : NULL)->save();
}
示例10: testTaxonomyImageAccess
public function testTaxonomyImageAccess()
{
$user = $this->drupalCreateUser(array('administer site configuration', 'administer taxonomy', 'access user profiles'));
$this->drupalLogin($user);
// Create a term and upload the image.
$files = $this->drupalGetTestFiles('image');
$image = array_pop($files);
$edit['name[0][value]'] = $this->randomMachineName();
$edit['files[field_test_0]'] = drupal_realpath($image->uri);
$this->drupalPostForm('admin/structure/taxonomy/manage/' . $this->vocabulary->id() . '/add', $edit, t('Save'));
$this->drupalPostForm(NULL, ['field_test[0][alt]' => $this->randomMachineName()], t('Save'));
$terms = entity_load_multiple_by_properties('taxonomy_term', array('name' => $edit['name[0][value]']));
$term = reset($terms);
$this->assertText(t('Created new term @name.', array('@name' => $term->getName())));
// Create a user that should have access to the file and one that doesn't.
$access_user = $this->drupalCreateUser(array('access content'));
$no_access_user = $this->drupalCreateUser();
$image = File::load($term->field_test->target_id);
$this->drupalLogin($access_user);
$this->drupalGet(file_create_url($image->getFileUri()));
$this->assertResponse(200, 'Private image on term is accessible with right permission');
$this->drupalLogin($no_access_user);
$this->drupalGet(file_create_url($image->getFileUri()));
$this->assertResponse(403, 'Private image on term not accessible without right permission');
}
示例11: testPrivateFile
/**
* Tests file access for file uploaded to a private node.
*/
function testPrivateFile()
{
$type_name = 'article';
$field_name = strtolower($this->randomMachineName());
$this->createFileField($field_name, 'node', $type_name, array('uri_scheme' => 'private'));
// Create a field with no view access. See
// field_test_entity_field_access().
$no_access_field_name = 'field_no_view_access';
$this->createFileField($no_access_field_name, 'node', $type_name, array('uri_scheme' => 'private'));
$test_file = $this->getTestFile('text');
$nid = $this->uploadNodeFile($test_file, $field_name, $type_name, TRUE, array('private' => TRUE));
$node = node_load($nid, TRUE);
$node_file = file_load($node->{$field_name}->target_id);
// Ensure the file can be downloaded.
$this->drupalGet(file_create_url($node_file->getFileUri()));
$this->assertResponse(200, 'Confirmed that the generated URL is correct by downloading the shipped file.');
$this->drupalLogOut();
$this->drupalGet(file_create_url($node_file->getFileUri()));
$this->assertResponse(403, 'Confirmed that access is denied for the file without the needed permission.');
// Test with the field that should deny access through field access.
$this->drupalLogin($this->admin_user);
$nid = $this->uploadNodeFile($test_file, $no_access_field_name, $type_name, TRUE, array('private' => TRUE));
\Drupal::entityManager()->getStorage('node')->resetCache(array($nid));
$node = Node::load($nid);
$node_file = File::load($node->{$no_access_field_name}->target_id);
// Ensure the file cannot be downloaded.
$user = $this->drupalCreateUser(array('access content'));
$this->drupalLogin($user);
$this->drupalGet(file_create_url($node_file->getFileUri()));
$this->assertResponse(403, 'Confirmed that access is denied for the file without view field access permission.');
}
示例12: testSubRequestDependent
/**
* Test a gallery embedded in a view row that is dependent on the Juicebox
* cache.
*/
public function testSubRequestDependent()
{
$node = $this->node;
$xml_path = 'juicebox/xml/field/node/' . $node->id() . '/' . $this->instFieldName . '/_custom';
$xml_url = \Drupal::url('juicebox.xml_field', array('entityType' => 'node', 'entityId' => $node->id(), 'fieldName' => $this->instFieldName, 'displayName' => '_custom'));
// Get the urls to the test image and thumb derivative used by default.
$uri = \Drupal\file\Entity\File::load($node->{$this->instFieldName}[0]->target_id)->getFileUri();
$test_image_url = entity_load('image_style', 'juicebox_medium')->buildUrl($uri);
$test_thumb_url = entity_load('image_style', 'juicebox_square_thumb')->buildUrl($uri);
// Check for correct embed markup. This will also prime the cache.
$content = $this->drupalGet('juicebox_test_row_formatter');
$this->assertRaw(trim(json_encode(array('configUrl' => $xml_url)), '{}"'), 'Gallery setting found in Drupal.settings.');
$this->assertRaw('id="node--' . $node->id() . '--' . str_replace('_', '-', $this->instFieldName) . '---custom"', 'Embed code wrapper found.');
$this->assertRaw(Html::escape($test_image_url), 'Test image found in embed code');
// Extract the xml-source values from the XML.
$matches = array();
// In the pattern below we have to use four (yeah, FOUR) backslashes to
// match a SINGLE literal backslash. Our source will contain an encoded
// (JSON) "&" character as "\u0026", but we don't want the regex to confuse
// that with an actaul "&" char in the pattern itself.
preg_match('|xml-source-path=([a-z1-9_-]+)\\\\u0026xml-source-id=([a-z1-9-]+)|', $content, $matches);
$this->assertNotNull($matches[1], 'xml-source-path value found in Drupal.settings.');
$this->assertNotNull($matches[2], 'xml-source-id value found in Drupal.settings.');
// Check for correct XML. This example is dependent on a sub-request XML
// lookup, so everything below would fail without that feature.
$this->drupalGet($xml_path, array('query' => array('xml-source-path' => $matches[1], 'xml-source-id' => $matches[2])));
$this->assertRaw('<?xml version="1.0" encoding="UTF-8"?>', 'Valid XML detected.');
$this->assertRaw('imageURL="' . Html::escape($test_image_url), 'Test image found in XML.' . $test_image_url);
$this->assertRaw('thumbURL="' . Html::escape($test_thumb_url), 'Test thumbnail found in XML.' . $test_thumb_url);
$this->assertRaw('backgroundcolor="green"', 'Custom background setting from pseudo field instance config found in XML.');
}
示例13: testUser
/**
* Tests the Drupal6 user to Drupal 8 migration.
*/
public function testUser()
{
$users = Database::getConnection('default', 'migrate')->select('users', 'u')->fields('u')->condition('uid', 0, '>')->execute()->fetchAll();
foreach ($users as $source) {
// Get roles directly from the source.
$rids = Database::getConnection('default', 'migrate')->select('users_roles', 'ur')->fields('ur', array('rid'))->condition('ur.uid', $source->uid)->execute()->fetchCol();
$roles = array(RoleInterface::AUTHENTICATED_ID);
$id_map = $this->getMigration('d6_user_role')->getIdMap();
foreach ($rids as $rid) {
$role = $id_map->lookupDestinationId(array($rid));
$roles[] = reset($role);
}
/** @var \Drupal\user\UserInterface $user */
$user = User::load($source->uid);
$this->assertIdentical($source->uid, $user->id());
$this->assertIdentical($source->name, $user->label());
$this->assertIdentical($source->mail, $user->getEmail());
$this->assertIdentical($source->created, $user->getCreatedTime());
$this->assertIdentical($source->access, $user->getLastAccessedTime());
$this->assertIdentical($source->login, $user->getLastLoginTime());
$is_blocked = $source->status == 0;
$this->assertIdentical($is_blocked, $user->isBlocked());
// $user->getPreferredLangcode() might fallback to default language if the
// user preferred language is not configured on the site. We just want to
// test if the value was imported correctly.
$this->assertIdentical($source->language, $user->preferred_langcode->value);
$expected_timezone_name = $source->timezone_name ?: $this->config('system.date')->get('timezone.default');
$this->assertIdentical($expected_timezone_name, $user->getTimeZone());
$this->assertIdentical($source->init, $user->getInitialEmail());
$this->assertIdentical($roles, $user->getRoles());
// We have one empty picture in the data so don't try load that.
if (!empty($source->picture)) {
// Test the user picture.
$file = File::load($user->user_picture->target_id);
$this->assertIdentical(basename($source->picture), $file->getFilename());
} else {
// Ensure the user does not have a picture.
$this->assertFalse($user->user_picture->target_id, sprintf('User %s does not have a picture', $user->id()));
}
// Use the API to check if the password has been salted and re-hashed to
// conform to Drupal >= 7 for non-admin users.
if ($user->id() != 1) {
$this->assertTrue(\Drupal::service('password')->check($source->pass_plain, $user->getPassword()));
}
}
// Rollback the migration and make sure everything is deleted but uid 1.
(new MigrateExecutable($this->migration, $this))->rollback();
$users = Database::getConnection('default', 'migrate')->select('users', 'u')->fields('u', ['uid'])->condition('uid', 0, '>')->execute()->fetchCol();
foreach ($users as $uid) {
$account = User::load($uid);
if ($uid == 1) {
$this->assertNotNull($account, 'User 1 was preserved after rollback');
} else {
$this->assertNull($account);
}
}
}
示例14: getPreparedGeocodeValues
/**
* @inheritDoc
*/
public function getPreparedGeocodeValues(array $values = array())
{
foreach ($values as $index => $value) {
if ($value['target_id']) {
$values[$index]['value'] = \Drupal::service('file_system')->realpath(\Drupal\file\Entity\File::load($value['target_id'])->getFileUri());
}
}
return $values;
}
示例15: testNodeDisplay
/**
* Tests normal formatter display on node display.
*/
function testNodeDisplay()
{
$field_name = strtolower($this->randomMachineName());
$type_name = 'article';
$field_storage_settings = array('display_field' => '1', 'display_default' => '1', 'cardinality' => FieldStorageDefinitionInterface::CARDINALITY_UNLIMITED);
$field_settings = array('description_field' => '1');
$widget_settings = array();
$this->createFileField($field_name, 'node', $type_name, $field_storage_settings, $field_settings, $widget_settings);
// Create a new node *without* the file field set, and check that the field
// is not shown for each node display.
$node = $this->drupalCreateNode(array('type' => $type_name));
// Check file_default last as the assertions below assume that this is the
// case.
$file_formatters = array('file_table', 'file_url_plain', 'hidden', 'file_default');
foreach ($file_formatters as $formatter) {
$edit = array("fields[{$field_name}][type]" => $formatter);
$this->drupalPostForm("admin/structure/types/manage/{$type_name}/display", $edit, t('Save'));
$this->drupalGet('node/' . $node->id());
$this->assertNoText($field_name, format_string('Field label is hidden when no file attached for formatter %formatter', array('%formatter' => $formatter)));
}
$test_file = $this->getTestFile('text');
simpletest_generate_file('escaped-&-text', 64, 10, 'text');
$test_file = File::create(['uri' => 'public://escaped-&-text.txt', 'name' => 'escaped-&-text', 'filesize' => filesize('public://escaped-&-text.txt')]);
// Create a new node with the uploaded file.
$nid = $this->uploadNodeFile($test_file, $field_name, $type_name);
// Check that the default formatter is displaying with the file name.
$node_storage = $this->container->get('entity.manager')->getStorage('node');
$node_storage->resetCache(array($nid));
$node = $node_storage->load($nid);
$node_file = File::load($node->{$field_name}->target_id);
$file_link = array('#theme' => 'file_link', '#file' => $node_file);
$default_output = \Drupal::service('renderer')->renderRoot($file_link);
$this->assertRaw($default_output, 'Default formatter displaying correctly on full node view.');
// Turn the "display" option off and check that the file is no longer displayed.
$edit = array($field_name . '[0][display]' => FALSE);
$this->drupalPostForm('node/' . $nid . '/edit', $edit, t('Save and keep published'));
$this->assertNoRaw($default_output, 'Field is hidden when "display" option is unchecked.');
// Add a description and make sure that it is displayed.
$description = $this->randomMachineName();
$edit = array($field_name . '[0][description]' => $description, $field_name . '[0][display]' => TRUE);
$this->drupalPostForm('node/' . $nid . '/edit', $edit, t('Save and keep published'));
$this->assertText($description);
// Ensure the filename in the link's title attribute is escaped.
$this->assertRaw('title="escaped-&-text.txt"');
// Test that fields appear as expected after during the preview.
// Add a second file.
$name = 'files[' . $field_name . '_1][]';
$edit[$name] = drupal_realpath($test_file->getFileUri());
// Uncheck the display checkboxes and go to the preview.
$edit[$field_name . '[0][display]'] = FALSE;
$edit[$field_name . '[1][display]'] = FALSE;
$this->drupalPostForm("node/{$nid}/edit", $edit, t('Preview'));
$this->clickLink(t('Back to content editing'));
$this->assertRaw($field_name . '[0][display]', 'First file appears as expected.');
$this->assertRaw($field_name . '[1][display]', 'Second file appears as expected.');
}