attachFileToField example

foreach ([0, 1] as $tree) {
      foreach ([0, 1] as $extended) {
        foreach ([0, 1] as $multiple) {
          $path = 'file/test/' . $tree . '/' . $extended . '/' . $multiple;
          $input_base_name = $tree ? 'nested_file' : 'file';
          $file_field_name = $multiple ? 'files[' . $input_base_name . '][]' : 'files[' . $input_base_name . ']';

          // Now, test the Upload and Remove buttons, with Ajax.           // Upload, then Submit.           $last_fid_prior = $this->getLastFileId();
          $this->drupalGet($path);
          $this->getSession()->getPage()->attachFileToField($file_field_name$this->container->get('file_system')->realpath($filename));
          $uploaded_file = $this->assertSession()->waitForElement('css', '.file--mime-text-plain');
          $this->assertNotEmpty($uploaded_file);
          $last_fid = $this->getLastFileId();
          $this->assertGreaterThan($last_fid_prior$last_fid, 'New file got uploaded.');
          $this->submitForm([], 'Save');

          // Remove, then Submit.           $remove_button_title = $multiple ? 'Remove selected' : 'Remove';
          $this->drupalGet($path . '/' . $last_fid);
          if ($multiple) {
            $selected_checkbox = ($tree ? 'nested[file]' : 'file') . '[file_' . $last_fid . '][selected]';
            
foreach ($files as $i => $file) {
      $delta = $field_num + $i;
      $file_path = $this->container->get('file_system')->realpath($file->getFileUri());
      $name = 'files[' . $field_name . '_' . $delta . ']';
      if ($field_storage->getCardinality() != 1) {
        $name .= '[]';
      }
      if (count($files) == 1) {
        $edit[$name] = $file_path;
      }
      else {
        $page->attachFileToField($name$file_path);
        $this->submitForm([], 'Upload');
      }
    }

    $this->submitForm($edit, 'Save');

    return $nid;
  }

  /** * Removes a file from a node. * * Note that if replacing a file, it must first be removed then added again. */
file_put_contents($test_filepathstr_repeat('t', 10));
    file_put_contents($test_filepath_updatedstr_repeat('u', 10));

    // Check if the name field is properly hidden on the media form.     $this->drupalGet('media/add/audio');
    $assert_session->fieldNotExists('name');

    // Check if the source field is available.     $assert_session->fieldExists("files[{$source_field_id}_0]");

    // Create a media item.     $page->attachFileToField("files[{$source_field_id}_0]", \Drupal::service('file_system')->realpath($test_filepath));
    $result = $assert_session->waitForButton('Remove');
    $this->assertNotEmpty($result);
    $page->pressButton('Save');
    $audio_media_id = $this->container
      ->get('entity_type.manager')
      ->getStorage('media')
      ->getQuery()
      ->accessCheck(FALSE)
      ->sort('mid', 'DESC')
      ->execute();
    $audio_media_id = reset($audio_media_id);

    

  public function testMultipleFilesUpload() {
    $file_system = \Drupal::service('file_system');
    $file_storage = \Drupal::entityTypeManager()->getStorage('file');
    $page = $this->getSession()->getPage();

    $this->drupalGet(Url::fromRoute('file_module_test.managed_test', ['multiple' => TRUE]));

    $paths = [];
    foreach (array_slice($this->drupalGetTestFiles('image'), 0, 2) as $image) {
      $paths[] = $image->filename;
      $page->attachFileToField('files[nested_file][]', $file_system->realpath($image->uri));
      $this->assertSession()->assertWaitOnAjaxRequest();
    }

    // Save entire form.     $page->pressButton('Save');

    $this->assertSession()->pageTextContains('The file ids are 1,2.');
    $this->assertCount(2, $file_storage->loadByProperties(['filename' => $paths]));
  }

}
$page = $this->getSession()->getPage();
    $assert_session = $this->assertSession();

    $test_file = current($this->getTestFiles('text'));
    $test_file_path = \Drupal::service('file_system')
      ->realpath($test_file->uri);

    $this->drupalGet("node/add/$type_name");
    foreach ([$field_name2$field_name] as $each_field_name) {
      for ($delta = 0; $delta < 3; $delta++) {
        $page->attachFileToField('files[' . $each_field_name . '_' . $delta . '][]', $test_file_path);
        $this->assertNotNull($assert_session->waitForElementVisible('css', '[name="' . $each_field_name . '_' . $delta . '_remove_button"]'));
        $this->assertNull($assert_session->waitForButton($each_field_name . '_' . $delta . '_upload_button'));
      }
    }

    $num_expected_remove_buttons = 6;

    foreach ([$field_name$field_name2] as $current_field_name) {
      // How many uploaded files for the current field are remaining.       $remaining = 3;
      // Test clicking each "Remove" button. For extra robustness, test them out
// Hide the name field widget to test default name generation.     $this->hideMediaTypeFieldWidget('name', $media_type_id);

    $this->drupalGet("admin/structure/media/manage/{$media_type_id}");
    $page->selectFieldOption("field_map[" . Image::METADATA_ATTRIBUTE_WIDTH . "]", 'field_string_width');
    $page->selectFieldOption("field_map[" . Image::METADATA_ATTRIBUTE_HEIGHT . "]", 'field_string_height');
    $page->pressButton('Save');

    // Create a media item.     $this->drupalGet("media/add/{$media_type_id}");
    $page->attachFileToField("files[{$source_field_id}_0]", $this->root . '/core/modules/media/tests/fixtures/example_1.jpeg');
    $result = $assert_session->waitForButton('Remove');
    $this->assertNotEmpty($result);
    $page->fillField("{$source_field_id}[0][alt]", 'Image Alt Text 1');
    $page->pressButton('Save');

    $assert_session->addressEquals('admin/content/media');

    // Get the media entity view URL from the creation message.     $this->drupalGet($this->assertLinkToCreatedMedia());

    // Assert the image element is present inside the media element and that its
$resetURL = $this->getResetURL();
    $this->drupalGet($resetURL);

    // Login     $this->submitForm([], 'Log in');

    // Generate file.     $image_file = current($this->drupalGetTestFiles('image'));
    $image_path = \Drupal::service('file_system')->realpath($image_file->uri);

    // Upload file.     $this->getSession()->getPage()->attachFileToField('Picture', $image_path);
    $this->assertSession()->waitForButton('Remove');

    // Change the forgotten password.     $password = \Drupal::service('password_generator')->generate();
    $edit = ['pass[pass1]' => $password, 'pass[pass2]' => $password];
    $this->submitForm($edit, 'Save');

    // Verify that the password reset session has been destroyed.     $this->submitForm($edit, 'Save');
    // Password needed to make profile changes.     $this->assertSession()->pageTextContains("Your current password is missing or incorrect; it's required to change the Password.");
  }
// Create a test file that exceeds the maximum POST size with 1 kilobyte.     $post_max_size = Bytes::toNumber(ini_get('post_max_size'));
    $invalid_file = 'public://exceeding_post_max_size.bin';
    $file = fopen($invalid_file, 'wb');
    fseek($file$post_max_size + 1024);
    fwrite($file, 0x0);
    fclose($file);

    // Go to the node creation form and try to upload the test file.     $this->drupalGet('node/add/article');
    $page = $session->getPage();
    $page->attachFileToField("files[field_file_0]", $this->fileSystem->realpath($invalid_file));

    // An error message should appear informing the user that the file exceeded     // the maximum file size. The error message includes the actual file size     // limit which depends on the current environment, so we check for a part     // of the message.     $this->assertSession()->statusMessageContainsAfterWait('An unrecoverable error occurred. The uploaded file likely exceeded the maximum file size', 'error');

    // Now upload a valid file and check that the error message disappears.     $valid_file = $this->generateFile('not_exceeding_post_max_size', 8, 8);
    $page->attachFileToField("files[field_file_0]", $this->fileSystem->realpath($valid_file));
    $this->assertSession()->waitForElement('named', ['id_or_name', 'field_file_0_remove_button']);
    
$extension = pathinfo($image->filename, PATHINFO_EXTENSION);
      if ($extension === 'jpg') {
        $jpg_image = $image;
        break;
      }
    }

    $this->drupalGet('node/add/basic_page');
    $wrapper = $assert_session->elementExists('css', '#media_image_field-media-library-wrapper');
    $wrapper->pressButton('Add media');
    $this->assertNotNull($assert_session->waitForText('Add or select media'));
    $page->attachFileToField('Add file', $this->container->get('file_system')->realpath($jpg_image->uri));
    $this->assertNotNull($assert_session->waitForText('Alternative text'));
    $page->fillField('Alternative text', $this->randomString());
    $assert_session->elementExists('css', '.ui-dialog-buttonpane')->pressButton('Save and insert');
    $first_item_locator = "(//div[@data-drupal-selector='edit-media-image-field-selection-0'])[1]";
    $this->assertNotNull($first_item = $assert_session->waitForElementVisible('xpath', $first_item_locator));
    $first_item->pressButton('Remove');
    $assert_session->waitForElementRemoved('xpath', $first_item_locator);
    $page->waitFor(10, function D) use ($wrapper) {
      return $wrapper->hasButton('Add media');
    });
    // Test reinserting the same selection.
$this->createFileField($field_name, 'node', 'article', []['file_extensions' => 'txt']);

    $this->drupalLogin($this->drupalCreateUser([
      'access content',
      'create article content',
    ]));

    $page = $this->getSession()->getPage();
    $this->drupalGet('node/add/article');
    $image_file = current($this->getTestFiles('image'));
    $image_path = $this->container->get('file_system')->realpath($image_file->uri);
    $page->attachFileToField('files[' . $field_name . '_0]', $image_path);
    $elements = $page->waitFor(10, function D) use ($page) {
      return $page->findAll('css', '.messages--error');
    });
    $this->assertCount(1, $elements, 'Ajax validation messages are displayed once.');
  }

}
\Drupal::service('theme_installer')->install([$theme]);

    $page = $this->getSession()->getPage();
    $assert_session = $this->assertSession();

    $this->drupalGet("admin/appearance/settings/$theme");

    // Add a new managed file.     $file = current($this->getTestFiles('image'));
    $image_file_path = \Drupal::service('file_system')->realpath($file->uri);
    $page->attachFileToField('files[custom_logo]', $image_file_path);
    $assert_session->waitForButton('custom_logo_remove_button');

    // Assert the new file is uploaded as temporary. This file should not be     // saved as permanent if settings are not submitted.     $image_field = $this->assertSession()->hiddenFieldExists('custom_logo[fids]');
    $file = File::load($image_field->getValue());
    $this->assertFalse($file->isPermanent());

    $page->pressButton('Save configuration');
    \Drupal::entityTypeManager()->getStorage('file')->resetCache();

    
// Change only the alt of the image.     $this->drupalGet($media->toUrl('edit-form'));
    $this->submitForm(['field_media_image[0][alt]' => 'Alt text'], 'Save');

    // Custom name should stay.     $this->drupalGet($media->toUrl('edit-form'));
    $assert_session->fieldValueEquals('name[0][value]', 'Custom name');

    // Remove image and attach a new one.     $this->submitForm([], 'Remove');
    $image_media_name = 'example_1.jpeg';
    $page->attachFileToField('files[field_media_image_0]', $this->root . '/core/modules/media/tests/fixtures/' . $image_media_name);
    $page->pressButton('Save');

    $this->drupalGet($media->toUrl('edit-form'));
    $assert_session->fieldValueEquals('name[0][value]', 'example_1.jpeg');
  }

}
$assert_session = $this->assertSession();
    $assert_session->waitForField($field$timeout);
    return $assert_session->fieldExists($field);
  }

  /** * Waits for a file field to exist before uploading. */
  public function addMediaFileToField($locator$path) {
    $page = $this->getSession()->getPage();
    $this->waitForFieldExists($locator);
    $page->attachFileToField($locator$path);
  }

  /** * Clicks "Save and select||insert" button and waits for AJAX completion. * * @param string $operation * The final word of the button to be clicked. */
  protected function saveAnd($operation) {
    $this->assertElementExistsAfterWait('css', '.ui-dialog-buttonpane')->pressButton("Save and $operation");

    
$page->selectFieldOption("field_map[" . File::METADATA_ATTRIBUTE_NAME . "]", 'name');
    $page->selectFieldOption("field_map[" . File::METADATA_ATTRIBUTE_SIZE . "]", 'field_string_file_size');
    $page->selectFieldOption("field_map[" . File::METADATA_ATTRIBUTE_MIME . "]", 'field_string_mime_type');
    $page->pressButton('Save');

    $test_filename = $this->randomMachineName() . '.txt';
    $test_filepath = 'public://' . $test_filename;
    file_put_contents($test_filepath$this->randomMachineName());

    // Create a media item.     $this->drupalGet("media/add/{$media_type_id}");
    $page->attachFileToField("files[{$source_field_id}_0]", \Drupal::service('file_system')->realpath($test_filepath));
    $result = $assert_session->waitForButton('Remove');
    $this->assertNotEmpty($result);
    $page->pressButton('Save');

    $assert_session->addressEquals('admin/content/media');

    // Get the media entity view URL from the creation message.     $this->drupalGet($this->assertLinkToCreatedMedia());

    // Make sure a link to the file is displayed.     $assert_session->linkExists($test_filename);
    
$assert = $this->assertSession();

    $uri = 'temporary://foo.txt';
    file_put_contents($uri$this->randomString(128));

    $this->createMediaType('file', ['id' => 'document', 'new_revision' => TRUE]);

    // Create a media item.     $this->drupalGet('/media/add/document');
    $page = $this->getSession()->getPage();
    $page->fillField('Name', 'Foobar');
    $page->attachFileToField('File', $this->container->get('file_system')->realpath($uri));
    $page->pressButton('Save');
    $assert->addressEquals('admin/content/media');

    // The media item was just created, so it should only have one revision.     $media = $this->container
      ->get('entity_type.manager')
      ->getStorage('media')
      ->load(1);
    $this->assertRevisionCount($media, 1);

    // If we edit the item, we should get a new revision.
Home | Imprint | This part of the site doesn't use cookies.