Wednesday, March 26, 2025
HomeiOS DevelopmentLearn how to construct a Feather CMS module?

Learn how to construct a Feather CMS module?

[ad_1]

On this tutorial I am going to present you the best way to create a customized person module with an admin interface for Feather utilizing Swift 5 and Vapor 4.

Vapor


Module era utilizing Swift templates

There may be an open supply template based mostly generator instrument for Swift that I’ve created, as a result of I wanted one thing to shortly arrange each VIPER and Feather modules. We’re going to use this generator to begin constructing our customized Feather module. You possibly can set up Swift template by the command line:


git clone https://github.com/BinaryBirds/swift-template.git
cd swift-template
make set up


Now we simply want a starter template, thankfully there’s a template obtainable on GitHub that you need to use for producing modules which are suitable with the newest model of Feather CMS. 🪶

We’re going to set up this template with the next command:



swift template set up https://github.com/feathercms/feather-module-template -g


Now we will bootstrap our customized module by way of the next command:


swift template generate MyModule --use feather-module --output ~/


You possibly can alter the the title of the module, use an different template (have to be put in regionally or globally) and specify the output listing the place you need to save the module information.





Constructing a information module for Feather CMS

In Feather CMS you possibly can constructing a function wealthy module in only a few minutes. That is proper, I am going to present you the best way to make one utilizing Swift template and the Feather module template starter equipment. To begin with you may have to seize Feather CMS from GitHub and generate a brand new module utilizing the generator.


git clone https://github.com/feathercms/feather/
cd feather
swift template generate Information -u feather-module -o ./Sources/Feather/Modules
open Bundle.swift


Replace your Swift package deal dependencies. You need to use the Swift Bundle Supervisor and the command line (swift package deal replace) in case you are constructing the server with out Xcode. Alternatively you possibly can open the package deal manifest file and wait till Xcode resolves the dependencies. 📦


Earlier than we run the app, just remember to have created a neighborhood .env or .env.improvement file that Feather can use to run the server.


BASE_URL="http://localhost:8080"


BASE_PATH="/path/to/feather/"


When utilizing Xcode, please double examine that you have set a customized working listing. ⚠️

Time to allow our newly created module, open to the important.swift file and append the NewsBuilder() occasion to the module configuration array. This may allow the pattern information module. Now should you run Feather, the brand new module ought to work by default, however earlier than we really check out all the pieces we’re going to alter the generated information module supply just a bit bit. 🔨



Mannequin definition

Let’s begin by altering the mannequin definition for our information entries. This may permit us to retailer information objects within the persistent database utilizing the underlying Fluent framework. The generated information module will include a NewsModel, we simply want to increase this mannequin with a number of extra fields.


import FeatherCore

closing class NewsModel: ViperModel {
    typealias Module = NewsModule

    static let title = "information"

    struct FieldKeys {
        static var title: FieldKey { "title" }
        static var imageKey: FieldKey { "image_key" }
        static var excerpt: FieldKey { "excerpt" }
        static var content material: FieldKey { "content material" }
    }

    

    @ID() var id: UUID?
    @Subject(key: FieldKeys.title) var title: String
    @Subject(key: FieldKeys.imageKey) var imageKey: String
    @Subject(key: FieldKeys.excerpt) var excerpt: String
    @Subject(key: FieldKeys.content material) var content material: String

    init() { }

    init(id: UUID? = nil,
         title: String,
         imageKey: String,
         excerpt: String,
         content material: String)
    {
        self.id = id
        self.title = title
        self.imageKey = imageKey
        self.excerpt = excerpt
        self.content material = content material
    }
}


We outlined our Fluent database mannequin with the assistance of Swift property wrappers (@ID, @Subject). They are going to permit Fluent to learn and write columns within the represented database desk, so we do not have to jot down SQL queries, however we will entry the entries by a a lot increased degree (ORM) abstraction layer. Fairly commonplace Vapor and Fluent stuff these days. 🙃

The id is a singular identifier, we will save the information title as a String, the imageKey is a particular property for saving picture URLs and the excerpt goes to be a brief “sneak-peak” of your complete content material. Now we simply have to jot down a migration script, as a result of in Vapor we’ve got to create or replace our database tables earlier than we may use the mannequin.

import Vapor
import Fluent

struct NewsMigration_v1_0_0: Migration {

    func put together(on db: Database) -> EventLoopFuture<Void> {
        db.schema(NewsModel.schema)
            .id()
            .area(NewsModel.FieldKeys.title, .string, .required)
            .area(NewsModel.FieldKeys.imageKey, .string, .required)
            .area(NewsModel.FieldKeys.excerpt, .string, .required)
            .area(NewsModel.FieldKeys.content material, .string, .required)
            .create()
    }

    func revert(on db: Database) -> EventLoopFuture<Void> {
        db.schema(NewsModel.schema).delete()
    }
}

This migration script will create the required fields contained in the information desk and if vital we will revert the method by deleting your complete desk.


Metadata in Feather CMS

In Feather CMS all the pieces that may be publicly accessed by the web page must have an related metadata object. This metadata object is answerable for managing the general public url (slug) and visibility of the referenced entity, it additionally shops many extra Search engine optimization associated particulars.

Something can develop into a metadata reference, we simply must implement a particular protocol on the item that we need to use as a frontend content material, plus we’ve got to setup a customized middleware in an effort to feed the metadata mannequin with some primary details about the refenreced object.

The generated template offers a default metadata represantation for the pattern mannequin, we simply have to increase the NewsModel+Metadata.swift file with the brand new fields that we added to our mannequin. This fashion our referenced metadata can know much more data concerning the information feed merchandise.


import FeatherCore

extension NewsModel: MetadataRepresentable {

    var metadata: Metadata {
        .init(slug: Self.title + "https://theswiftdev.com/" + title.slugify(),
              title: title,
              excerpt: excerpt,
              imageKey: imageKey)
    }
}

This MetadataRepresentable protocol is used after we save a information mannequin, Feather will create an related Metadata object with the returned title, excerpt and imageKey values. This connection works robotically should you register a database middleware within the boot operate of your module file.


func boot(_ app: Software) throws {
    
    app.databases.middleware.use(MetadataModelMiddleware<NewsModel>())

    
}

Utilizing the metadata API is an effective way to have good Search engine optimization-friendly public pages in your web site backed by your individual enterprise fashions with out considering an excessive amount of concerning the underlying knowledge construction.


Enter types

The default template additionally offers us the power to handle the pattern mannequin through the use of the CMS. Now we have to increase this performance a bit, as a result of we have added some additional fields.

The LeafRepresentable protocol is a part of the Leaf framework, it permits us to render fashions utilizing the template engine. Now we have so as to add our personal properties contained in the NewsModel+View.swift file.

import FeatherCore

extension NewsModel: LeafDataRepresentable {

    var leafData: LeafData {
        .dictionary([
            "id": id,
            "title": title,
            "imageKey": imageKey,
            "excerpt": excerpt,
            "content": content,
        ])
    }
}

This transformation will permit us to checklist, create, replace or view our mannequin with all of the obtainable fields utilizing the Content material Administration System. The generated template offers us all the CRUD operations without spending a dime, however the interface solely works with the title area, so we’ve got so as to add the opposite newly created properties if we would like to have the ability to fully handle our mannequin.


The ModelForm protocol permits us to offer edit (create, replace) performance for a given mannequin by the CMS. The shape has to outline the fields that you need to use within the Leaf template file to render them visually. The sphere definitions within the type are all about knowledge illustration, however they do not specify the appear and feel of the gadgets on the admin interface. In different phrases these fields are usually not vital view representations, however extra like knowledge switch objects. We’re going to put the precise view right into a separate Leaf template file in a while. 🍃


The sphere sorts are predefined objects within the ViewKit framework, a FormField is an object that encapsulates a generic worth and an elective error message. The FileFormField object is used to switch file knowledge while you need to use a file add area inside your type. After you specified the keys that you just need to use to ship the values, it’s important to checklist these type fields utilizing the fields variable. Every little thing what’s listed as a area shall be robotically validated based mostly on the constraint that you have placed on every area (required, size, and so on.).


If you wish to edit a metadata representable mannequin you normally need to ship the metadata data with the mannequin knowledge, you possibly can fetch the referenced metadata object through the use of the findMetadata methodology on a Fluent mannequin, this can load the reference asynchronously. The initialize methodology is a perfect place to carry out async init duties. You too can override the leafData variable to ship extra info subsequent to the modelId, fields and notification keys.


For the reason that type is tied to an underlying mannequin, we additionally must learn the mannequin knowledge earlier than we render our type so we will render authentic area values, and after the person submits the shape we would need to write the enter date to the mannequin. In fact the write methodology shall be referred to as solely when the incoming type fields are legitimate. You possibly can carry out extra database checks if in case you have particular validation wants earlier than you really save a mannequin.


The very last item that we need to do is picture processing. We are able to use the processAfterFields methodology to add our picture into a brief location, then earlier than the save methodology is known as (after the fields are validated), we will use the willSave operate to save lots of the picture to a closing location and replace our mannequin with the important thing that represents our uploaded picture file. You need to use this key in a while to render the picture file with the assistance of the Liquid file storage element. 📁


import FeatherCore

closing class NewsEditForm: ModelForm {

    typealias Mannequin = NewsModel

    var modelId: UUID?
    var picture = FileFormField(key: "picture").required()
    var title = FormField<String>(key: "title").required().size(max: 250)
    var excerpt = FormField<String>(key: "excerpt").required().size(max: 250)
    var content material = FormField<String>(key: "content material").required()
    var notification: String?

    var metadata: Metadata?

    var fields: [FormFieldRepresentable] {
        [image, title, excerpt, content]
    }

    var leafData: LeafData {
        .dictionary([
            "modelId": modelId?.encodeToLeafData() ?? .string(nil),
            "fields": fieldsLeafData,
            "notification": .string(notification),
            "metadata": metadata?.leafData ?? .dictionary(nil),
        ])
    }

    init() {}

    func initialize(req: Request) -> EventLoopFuture<Void> {
        var future = req.eventLoop.future()
        if let id = modelId {
            future = Mannequin.findMetadata(reference: id, on: req.db).map { [unowned self] in metadata = $0 }
        }
        return future
    }

    func processAfterFields(req: Request) -> EventLoopFuture<Void> {
        picture.uploadTemporaryFile(req: req)
    }

    func learn(from enter: Mannequin)  {
        title.worth = enter.title
        excerpt.worth = enter.excerpt
        picture.worth.originalKey = enter.imageKey
        content material.worth = enter.content material
    }

    func write(to output: Mannequin) {
        output.title = title.worth!
        output.excerpt = excerpt.worth!
        output.content material = content material.worth!
    }

    func willSave(req: Request, mannequin: Mannequin) -> EventLoopFuture<Void> {
        picture.save(to: Mannequin.path, req: req).map { key in
            if let key = key {
                mannequin.imageKey = key
            }
        }
    }
}


The principle purpose why types exists is that I wished to separate tasks. A type can assist the controller to show a display contained in the CMS utilizing a mannequin, this fashion our controller information shall be smaller and cleaner. Kinds cannot render themselves, so that they nonetheless want a controller object that may management them and a router to register the required URLs that we will use to hook them as much as the admin interface. Kinds normally want one URL that may be reached by a GET request for rendering the preliminary type and one other one which can be utilized to POST (submit) the shape. ↗️




Admin views

The pattern module already contains the templates that we will have to help information administration. Templates are positioned within the Bundle/Templates folder underneath the module listing. The Admin folder comprises subfolders with mannequin names and each single mannequin that we need to handle ought to have a view, edit, delete and checklist template file for the CRUD operations. 🔨


These templates comply with the identical sample. Each single on of them begins with a dictionary definiton that’s utilized by one other template (inlined on the finish of the file) to render the view based mostly on the values contained in the dictionary. The admin module offers us plenty of templates that we will use to simplify issues. There are pre-baked templates for enter types (Admin/Kind), lists (Admin/Desk), to current affirmation earlier than delete (Admin/Delete) operation and to easily view the small print (Admin/Element) of a mannequin. You must reap the benefits of these templates if attainable. 😉


The admin module additionally offers us reusable type fields. Let’s alter the Edit template, we will add numerous enter fields for the shape fields that we outlined beforehand.


#outline(fields):
    #var(area = nil)

    #(area = ["id": "image", "data": fields.image, "accept": "image/*", "required": true])
    #inline("Admin/Fields/File")

    #(area = ["id": "title", "required": true, "data": fields.title])
    #inline("Admin/Fields/Textual content")

    #(area = ["id": "excerpt", "size": "s", "data": fields.excerpt])
    #inline("Admin/Fields/Textarea")

    #(area = ["id": "content", "size": "xl", "data": fields.content])
    #inline("Admin/Fields/Textarea")

#enddefine


Contained in the Bundle/Templates/Admin/Information/Edit.html file we simply have so as to add three new fields to signify our type fiels as HTML type parts. You need to use all form of built-in type parts, plus each single type is CSRF and double-submission protected, which means you’re secure from CSRF assaults by default should you comply with this design sample.



Now should you run the applying many of the performance ought to work with the newly created fields, however earlier than we accomplish that, we must always speak about admin controllers.



Admin controllers


The underlying ViperKit framework can assist us so much with the required controller setup. Happily Feather comes with an extension that makes issues much more easy if we simply need to present a CRUD interface for a given mannequin. In case you check out the NewsAdminController you may see that you just solely must setup the referneced module, mannequin and type sorts in an effort to make issues work. 💪


You possibly can prolong the performance of controllers by implementing particular lifecycle strategies, for instance we will delete the uploaded picture file from the file storage through the use of the beforeDelete methodology. Additionally it is attainable to increase the checklist performance or alter the replace, create strategies, it’s best to check out the AdminViewController protocol in case you are within the particulars.


import FeatherCore
import Fluent

struct NewsAdminController: ViperAdminViewController {

    typealias Module = NewsModule
    typealias Mannequin = NewsModel
    typealias CreateForm = NewsEditForm
    typealias UpdateForm = NewsEditForm

    func listQuery(search: String, queryBuilder: QueryBuilder<Mannequin>, req: Request) {
        queryBuilder.filter(.$title ~~ search)
    }

    func beforeDelete(req: Request, mannequin: Mannequin) -> EventLoopFuture<Mannequin> {
        req.fs.delete(key: mannequin.imageKey).map { mannequin }
    }
}


Lengthy story brief, an admin controller has all the pieces that you will have to handle your mannequin utilizing the CMS. It will present a listing, get, create, replace and delete view to your mannequin.




The frontend hooks


If you wish to show information entries on the frontend as devoted pages it’s important to implement some hook capabilities within the module file. Happily the bottom template already hooks up all the pieces, so we simply have to alter our templates to show extra knowledge.


The “frontend-page” hook can be utilized to fetch metadata objects for a given path and return a response if a mannequin exists for a given slug. This can be a nice strategy to render information entries in a Search engine optimization pleasant method. It’s attainable to create a separate view object an cross the request and the mannequin to it so it could possibly render the frontend web page based mostly on a template file.


We will add only one little additional modification to our frontend view. Would not be cool if we may help content material filters for the information entries? This fashion we may use the markdown format (if we allow the markdown module) to jot down the content material of a information merchandise. Here is the best way to do it.


struct NewsFrontendView {

    

    func information(_ information: NewsModel) -> EventLoopFuture<View> {
        var ctx = information.leafDataWithJoinedMetadata.dictionary!
        ctx["content"] = .string(information.filter(information.content material, req: req))
        return render("Information", [
            "news": .dictionary(ctx)
        ])
    }
}



You too can create *-page hooks, that you need to use to render customized templates with the assistance of the Frontend module. The frontend module comes with a web page mannequin, that you need to use to show pages, however it’s also attainable to attach a web page mannequin with Swift and Leaf code, that is the way it works in a nutshell. You register a hook operate (in our case “news-page”), then you definitely create a brand new web page with the next contents: [news-page]. This syntax implies that you need to name a Feather hook, as a substitute of rendering the contents of the web page, so the system will search for a hook operate with a sound response object and if it finds one, it’s going to use it to render the web page. 🤓


In our case, the “news-page” hook makes use of the Frontend/NewsList template, that’s answerable for displaying the checklist of the information entries. In case you click on on a listing merchandise, the frontend-page hook tries to load the information based mostly on the permalink (referenced metadata slug) and if there’s a match it’s going to render it utilizing the Frontend/Information template.


Feather makes use of the Peacock CSS library to place some fashion on HTML parts, we will improve our information checklist template. Simply alter the Frontend/NewList file, like this:


#outline(physique):

<div class="container">
    <div class="margin margin-bottom-xl">
        <header class="margin-bottom">
            <h1>Information checklist</h1>
            <p class="margin-top-zero">Learn the newest information</p>
        </header>

        <part>
            #for(merchandise in information):
            <div class="background margin-bottom padding shadow">
                <a href="/#(merchandise.metadata.slug)">
                    <img src="#(merchandise.imageKey.resolve())" class="size-width-full">
                    <h2 class="margin-top-zero">#(merchandise.title)</h2>
                    <p class="margin-top-zero">#(merchandise.excerpt)</p>
                </a>
            </div>
            #endfor
        </part>
    </div>
</div>

#enddefine

#inline("Frontend/Index")


The final step is to show a correct information entry with the brand new fields. Within the Frontend/Information file replace the physique and use the next structure for the entry web page.


#outline(physique):

<div class="container">
    <div class="margin margin-bottom-xl">
        <h1>#(information.title)</h1>
        <p class="margin-top-zero">#(information.excerpt)</p>
        <img src="#(information.imageKey.resolve())" class="size-width-full margin-vertical">
        #(information.content material)
    </div>
</div>

#enddefine

#inline("Frontend/Index")


Now should you construct and run all the pieces, first you may must run the installer, after that you would be able to log in to the admin interface and you may create & publish your very first information entry. You possibly can learn extra about the best way to use Feather CMS, simply learn the person handbook. As a free of charge it’s best to be capable to apply content material filters to your information merchandise, so you possibly can reap the benefits of the built-in markdown or the Swift syntax highlighter filters. 🤩





Abstract

On this tutorial we have created a model new module for Feather CMS utilizing loads of underlying frameworks and instruments. This may be arduous at first sight, however I actually love this strategy as a result of I can concentrate on defining my enterprise fashions as a substitute of taking good care of smaller particulars comparable to registering the required routes for enhancing a database entry. Feather CMS will cover this type of complexity and supply dynamic extension factors for constructing your admin interfaces. On the frontend facet you possibly can simply prolong the dynamic routing system, apply content material filters and even add your individual extension factors by hook capabilities.

There may be a lot extra to speak about, however this time I am going to cease proper right here, should you loved this tutorial please comply with me on twitter, subscribe to my publication or take into account supporting me by buying my Sensible Server Aspect Swift ebook on Gumroad.


[ad_2]

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments