Back to Start Page
Multiple media/file attachment: attachMany
With the attachMany function multiple files like images, movies or documents can be attached to a record of a database table. Media attachments are using built-in relations of WinterCMS. So it is very easy to implement them.
Todo Cheat Sheet
- Add code to model: public $attachMany = ['yourFieldName' ⇒ ['System\Models\File', 'public' ⇒ false]];
- Add new file upload widget to the backend form with 'yourFieldName' as field name
- Set at least allowed file extensions, width and height of image (if image files)
What it will look like
This is what a record with an attached file - an image in this case - will look like. See images at the right 'PageViews'.
Preparation
Prerequisites are
- an installed builder plugin
- any source code editor or e.g. the Developer Tools plugin with built-in Code editor like to be seen on the screenshoots
- a database table for records to attach the media to
- a form (at least in backend) to display the media
- some media already uploaded to the media manager or ready to do so
Required skills
- how to work with builder
- how to create a plugin with builder
- how to create tables and forms with builder
Step 1: Extend the base model
The base model requires to know the type of desired relation as well as the name of the relation. This name can be seen like a field name of a database-table.
The base model is located in the plugin directory, subdirectory models using the singular of the related db-table name. In our example in the namspace pds the plugin library with a book model this is:
/pds/library/models/book.php
Here, the attachMany relation has to be inserted:
These are the lines of code to add for the library example to add images of book covers with a new related field called pageviews.
Notice, that the chosen name for this new field must not exist already in the parent table where the related image will be attached to!
// add a relation for a SINGLE image, field name is 'cover' // this table must not have a field named 'cover' ! public $attachMany = [ 'pageviews' => ['System\Models\File', 'public' => false] ];
Step 2: Prepare the form
Next step is to complete the form with an additional field - the File upload widget to upload and display media and/or files:
Step 3: Upload media/files
Finally, in the backend form view of the plugin, a file can be uploaded by clicking on the file upload symbol - the area below the 'Page Views' title in the example:
Now the form is ready to attach multiple images and/or files to each record.
Back to Start Page