Table of Contents

Back to Start Page

Single media/file attachment: attachOne

With the attachOne function 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 $attachOne = ['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.



Preparation

Prerequisites are

Required skills

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 attachOne 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 cover.
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 $attachOne = [
        'cover' => ['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 'Cover Image' title in the example:


Now the form is ready to attach images and/or files to each record.



Back to Start Page