Jump to content

Importing files via API—halfway there!


Recommended Posts


I want to import files into a specific ProcessWire page that has a "files" field. I wrote this snippet and it successfully copies the files to the correct directory under /site/assets:

const PATH_PREFIX = '/path/to/files/';

$parent = pages()->get('/my-files-page');

But I also want the files to show up in ProcessWire’s admin panel for that page, linked to the "files" field.

Having done this with images, comments, and page reference fields, I know that it involves iterating through the files with code like this:

$newFile = new Pagefile();


…but I can’t figure out how to set the file information (name, description, extension, etc.), nor how to associate it with the file imported into the assets directory.

Luckily, I do have all the files referenced in a database, which I can access like so:

$files = database()->query("
    SELECT id, filename, title, category, permissions,
        description, downloads, status, modified, created,
        size, author
    FROM txp_file
    WHERE 1
    ORDER BY id

foreach ($files as $file) {
    // PROFIT!

But it’s not clear to me how to both import the file into the files field AND link the file’s metadata.

I’m sure that I am overlooking something simple, but I’m grateful for any guidance you might offer.

Thank you!

Link to comment
Share on other sites

$file = $page->getUnformatted('yourfield')->last();
$file->description = 'hello world';

getUnformatted ensures that you get the files as array and then retrieve the last file ? 

  • Like 3
Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

  • Recently Browsing   0 members

    • No registered users viewing this page.
  • Create New...