phpsymfonytypo3command-line-interfacetypo3-9.x

How to create a file relation in TYPO3 v9 in a CLI command from Symfony?


I created a migrate command to import data from another cms to TYPO3 with the new Symfony commands in TYPO3 9.5.4. The only problem is to create a relation between my imported data and their images. The example from the TYPO3 documentation does not work for me.

I create my new entity (e.g. Product) and call my method "addBackendFileRelation" to create a file relation between the uploaded file (record exists in the db) and my new product (record exists in the db).

public function addBackendFileRelation( int $uid, string $table, string $field, File $file ): bool {
    $resourceFactory = GeneralUtility::makeInstance( ResourceFactory::class );

    try {
        $fileObject = $resourceFactory->getFileObject( $file->getUid() );
        $objectUid = $fileObject->getUid();
    } catch ( FileDoesNotExistException $e ) {
        return false;
    }
  
    $record = BackendUtility::getRecord( $table, $uid );
    $newId = 'NEW1234';
    $data = [];
    $data['sys_file_reference'][$newId] = [
        'table_local' => 'sys_file',
        'uid_local' => $objectUid,
        'tablenames' => $table,
        'uid_foreign' => $uid,
        'fieldname' => $field,
        'pid' => $record['pid'],
    ];
    $data[$table][$uid] = [
        $field => $newId,
        'pid' => $record['pid'],
    ];
    $dataHandler = GeneralUtility::makeInstance( DataHandler::class );
    $dataHandler->start( $data, [] );
    $dataHandler->process_datamap();

    foreach ( $dataHandler->errorLog as $log ) {
        var_dump( $log );
    }

    $fileRefUid = $dataHandler->substNEWwithIDs[$newId];

    return (int)$fileRefUid > 0;
}

The errorLog from the DataHandler prints this:
[1.2.1]: Attempt to modify table 'sys_file_reference' without permission.

So what can I do to create the relation? Creating a backend user for cli doesn't work for me.

[EDIT] The Solution

With the example of the tutorial (link from the comments) it works. I put the method call before I try to create the relation:

    public function execute() {
      // authenticate CommandLineUserAuthentication user for DataHandler usage
      $GLOBALS['BE_USER']->backendCheckLogin();

      // [...]

      $this->addBackendFileRelation( $uid, $table, $field, $file );

      // [...]
    }

Solution

  • TYPO3 v9 has a static API method that shall be used:

    \TYPO3\CMS\Core\Core\Bootstrap::initializeBackendAuthentication();