Set file template when using Cloudconvert plugin

Hello!
I am using the following code from Cloudconvert to convert all uploaded gifs to mp4s:

function customConvertHook($file) {
    if($file->extension() == 'gif') {

        $file->cloudconvert(
            [
                'inputformat' => 'gif',
                'outputformat' => 'mp4',
                'save' => true, // keep file at cloud to avoid another download from cloudconvert-server
            ]
        );
    }
}

return [
    // ... other config settings
    'hooks' => [
        'file.create:after' => function($file) {
            customConvertHook($file);
        },
        'file.replace:after' => function($newFile, $oldFile) {
            customConvertHook($newFile);
        },
    ]
];

Is there a way to automatically set the template for all the newly created mp4 files (insert “Template: video-file” into the corresponding .txt file)?

Thanks!

You have to store the result of the conversion in a new variable like in the readme

function customConvertHook($file) {
    if($file->extension() == 'gif') {

        $newFile = $file->cloudconvert(
            [
                'inputformat' => 'gif',
                'outputformat' => 'mp4',
                'save' => true, // keep file at cloud to avoid another download from cloudconvert-server
            ]
        );
       return $newFile;
    }
    return null;
}

'file.create:after' => function($file) {
           $newFile = customConvertHook($file);
        },

You can then use $newFile->update(['template' => 'whatever' ) to set the template.

Don’t forget to apply some checks to make sure you have a file.

Thank you, works perfectly!

Sorry, I am still a beginner in php — in order to “to apply some checks to make sure you have a file”, do you mean like so?

  'file.create:after' => function($file) {
      $newFile = customConvertHook($file);
      if($newFile) {
        $newFile->update(['template' => 'video-file']);
      }         
  },

Yes, that should be sufficient.

1 Like

Perfect, thanks for all your help :partying_face: