Jump to content

Importing files via API—halfway there!


johnstephens
 Share

Recommended Posts

Hi!

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');
$parent->of(false);
$parent->filesManager->importFiles(PATH_PREFIX);
$parent->save();

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();

$parent->files->add($newFile);

…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

<?php
$page->of(false);
$page->yourfield->add("https://upload.wikimedia.org/wikipedia/commons/thumb/f/fa/Processwire_logo.svg/2560px-Processwire_logo.svg.png");
$file = $page->getUnformatted('yourfield')->last();
$file->description = 'hello world';
$page->save();

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
 Share

  • Recently Browsing   0 members

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