Silverstripe Version: 5.3
I upload a csv file with the following information:
FileName: “myfilename.pdf”, Title: “my custom file name”, ShortLinkTitle: “my short name”
DocumentCsvBulkLoader.php
use DocumentGroup;
use Document;
use SilverStripe\Dev\CsvBulkLoader;
use SilverStripe\Dev\BulkLoader_Result;
use SilverStripe\Assets\File;
use SilverStripe\Dev\Debug;
class DocumentCsvBulkLoader extends CsvBulkLoader {
private $group_id = null;
public $columnMap = [
'FileName' => '->importMyFileIdByName',
'Title' => 'Title',
'ShortLinkTitle' => 'ShortLinkTitle',
'DocumentGroup' => 'DocumentGroup.ID',
];
public $relationCallbacks = [
'DocumentGroup.ID' => [
'relationname' => 'DocumentGroup',
'callback' => 'getDocumentGroupByID'
]
];
// TODO
// public $duplicateChecks = [
// 'Title' => 'Title', // Title is no longer inserted in db
// ];
/**
* __construct - constructor, extended to take a target relation ID
*
* @param string $objectClass the class to generate objects
* @param int $groupID the relation ID
* @return void
*/
public function __construct($objectClass, $groupID)
{
$this->group_id = $groupID;
parent::__construct($objectClass);
}
/**
* processRecord - modified record processing function, injecting the target
* relation ID
*
* @param array $record the record from the CSV
* @param array $columnMap the column map to use
* @param BulkLoader_Result $results results
* @param boolean $preview = false wether preview is active
* @return int
*/
protected function processRecord($record, $columnMap, &$results, $preview = false)
{
$record['DocumentGroup'] = $this->group_id;
return parent::processRecord($record, $columnMap, $results, $preview);
}
/**
* getDocumentGroupByID - return the relation by the value in the column
*
* @param Document $obj the newly created object
* @param string|int $val the value in the column that triggered the callback
* @param array $record the entire row
* @return DocumentGroup|null
*/
public function getDocumentGroupByID(&$obj, $val, $record)
{
return DocumentGroup::get()->byID($val);
}
public function importMyFileIdByName(&$obj, $val, $record){
$myFile = File::get()->filter(['Name' => $val])->First();
if(!$myFile) {
user_error("Can't find file", E_USER_WARNING);
return;
}
$obj->MyFileID = $myFile->ID;
}
}
I tried
public $duplicateChecks = [
'Title' => 'Title', // => Title is no longer inserted in db
];
but this results in the Title not being added into the db anymore (which it does without the $duplicateChecks) and it doesn’t prevent it from getting added a second time when the same csv gets uploaded again.
Has anyone an idea how to achieve this?
I also struggle to debug this, as the debug shows only for a second or so.