1

I have read this resource about uploading a file to an asset field on an entry, but I believe I need to create the asset on its own because the asset has 2 custom fields associated with it that I want to define upon its creation. Is there not something like an 'assets/save-asset' action I can use to save an asset element without having to attach it to an entry?

Update: With Marion's help I'm a little closer. Side note: apparently 'assets/save-asset' is now depreciated in favor of 'assets/upload' so I'm using that. Here is my form:

              <form method='post' accept-charset='UTF-8' enctype='multipart/form-data'>
                {{ csrfInput() }}
                {{ actionInput('assets/upload') }}
                {{ hiddenInput('folderId', 7) }}
                {{ hiddenInput('title', 'cool image')}}
                <input name='file' type='file'>
                <input type='submit' value='submit'>
              </form>

But I am now getting a 400 Bad Request error with the message No file was uploaded. What am I doing wrong to not have my file attach correctly?

2

There is indeed an assets/save-asset controller. You will find it in vendor/craftcms/cms/src/controllers/AssetsController.php, the actionSaveAsset() function.

2
  • Ok great. For some reason I have a hard time reading the controller docs compared to other class docs. What is the name that I would need to use on my file upload field to place the file into the created asset element? If the answer is file then I suppose I should have tried to guess my way through this one lol.
    – Brimby
    Aug 8 '20 at 4:47
  • I edited my question to show where I'm at now. I was able to find the folderId by inspecting the folder in the CP.
    – Brimby
    Aug 8 '20 at 5:25
1

For anyone interested, I figured out that I had to name the asset field as "assets-upload" in order for it to work. I found this out by inspecting the asset upload button in the CP. Here is my working form code:

          <form method='post' accept-charset='UTF-8' enctype='multipart/form-data'>
            {{ csrfInput() }}
            {{ actionInput('assets/upload') }}
            {{ hiddenInput('folderId', 7) }}
            {{ hiddenInput('title', 'cool image')}}
            <input name="assets-upload" type='file'>
            <input type='submit' value='submit'>
          </form>

And remember, you can get your intended folderId also by inspecting the volume folders in the CP to see what the ID is.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.