How do I add a local file to an asset field with a dynamically generated sub-folder?
I've now worked out how to do this.

As I have a copy of the entry that I want to save the file to, I can work out what the name of the dynamic folder will be called.

// Generate target folder name
$targetFolderName = $entry-&gt;slug; // or whatever you want


Next, I see if the folder has already been created:

// See if target folder exists
// I'm searching on the name of the folder, plus the id of the parent folder
// (see question above for how to find this)
$targetFolder = craft()-&gt;assets-&gt;findFolder(array(
    'name' =&gt; $targetFolderName,
    'parent' =&gt; $parentFolder-&gt;id
));

if (!$targetFolder) {
    // target folder doesn't exist so we must create it
    $targetFolder = craft()-&gt;assets-&gt;createFolder($parentFolder-&gt;id, $targetFolderName);

    if ($targetFolder-&gt;status == 'success') {
        $targetFolderId = $targetFolder-&gt;getDataItem('folderId');
    } else {
        throw new Exception(Craft::t("Failed to create new folder."));
    }

} else {
    $targetFolderId = $targetFolder-&gt;id;
}

// Now I can move the PDF from its temporary location into out new assets folder
$response = craft()-&gt;assets-&gt;insertFileByLocalPath(
    $localFilePath, 
    $filename, 
    $targetFolderId, 
    AssetConflictResolution::KeepBoth
);


From here I followed the same code as in the question to add the asset to the asset field in $entry.