Demo Silverstripe and JavaScript sources for Lightning Talk "FormField Mini Apps" at StripeCon EU 2022

Overview

FormField Mini Apps

Watch the Lightning Talk on Youtube 📺

Demo repository for Lightning Talk "FormField Mini Apps with the JavaScript framework/lib/style of your choice" @ StripeCon EU 2022 in Stockholm.


[tl:dr]

You can solve complex workflow and UX use cases with JavaScript-powered Silverstripe FormFields (or Mini Apps).

Advantages:

👍 Can be used within Silverstripe EditForms

👍 Full flexibility when talking to async APIs

👍 Hydrate Mini App with "backend data" (e.g. user id, api key, ...)

🤯 Not forced to use jQuery Entwine or React

Recipe

1. Create your JavaScript app

Use Vue, Angular, Svelte, ... or even just plain Vanilla JavaScript. The sky is the limit. The official recommendation is to create it in the client/ directory of your project/module:

"More complex projects can alternatively contain frontend assets in a common client folder"

Make sure that single files are being generated for your fields/Mini Apps.

A vite-generated Vue app is used in this demo.

2. Wire your JavaScript app to Silverstripe

My recommendation is to create a custom FormField as a descendant of LiteralField. The following shows a somewhat generic solution.

<?php

namespace L51\Sandbox;

use SilverStripe\Forms\LiteralField;
use SilverStripe\View\Requirements;

class AppField extends LiteralField
{
    public function __construct($fieldName, $appName, $payload = [])
    {
        Requirements::css('app/client/dist/style.css');
        Requirements::javascript("app/client/dist/$appName.js");

        parent::__construct(
            $fieldName,
            "<div
                id='AppField_$fieldName'
                class='app-field $appName'
                data-payload='" . json_encode($payload) . "'></div>"
        );
    }
}

Example Usage:

<?php

use L51\Sandbox\AppField;
use SilverStripe\CMS\Model\SiteTree;
use SilverStripe\Core\Environment;

class Page extends SiteTree
{

    public function getCMSFields()
    {
        $fields = parent::getCMSFields();

        $fields->addFieldToTab(
            'Root.Main',
            AppField::create(
                'DemoGifField',
                'gif-field', // <--- will be used as css class selector and has to match first param of watchElement()
                [
                    'apiKey' => Environment::getEnv('TENOR_API_KEY'),
                    'topic'  => 'nerds'
                ]
            ),
            'Title'
        );

        return $fields;
    }
}

3. Data flows JavaScript app <---> Silverstripe

Silverstripe --> JavaScript app

As shown in the snippets above, AppField expects a third parameter $payload which should be an array. The JSON representation will be included in the wrapper-div's dataset scope (data-payload). This way the data will be accessible for the JavaScript app for hydration/configuration.

const render = (el: HTMLElement) => {
    const payload = JSON.parse(el.dataset.payload as string);

    createApp(GifField, {
        apiKey: payload.apiKey,
        topic: payload.topic
    }).mount(`#${el.id}`);;
}

JavaScript app --> Silverstripe

There are various ways to send data from the JavaScript app back to Silverstripe. You can easily create your own REST-style routes and make API requests or use the built-in GraphQL capabilities of Silverstripe.

One thing we should not forget about is the fact that FormFields are RequestHandlers and hence, siblings of Controllers (that's right!).

In our example:

AppField
 - LiteralField
  - DatalassField
   - FormField
    - RequestHandler 

Recommended reading: Zauberfisch was giving a nice talk about this topic ("SilverStripe FormFields and the magic beyond <input type=text/>") at StripeCon EU 2017 in Malta.

Hence, you can simply create actions on your custom FormField (e.g. AppField) and call them REST-style.

Another possible solution could be to take make your FormField getting picked up by an EditForms saveInto() traversal.

Feedback?

If you have comments or questions open an issue or reach out over the Silverstripe Slack to JZubero (me).

🖖

You might also like...
Sources of Api Bossbar for PocketMine-MP.
Sources of Api Bossbar for PocketMine-MP.

Sources of Api Bossbar for PocketMine-MP.

Mega list of 1 on 1 meeting questions compiled from a variety to sources

Mega list of 1 on 1 meeting questions compiled from a variety to sources

2022 edition of the inRage Theme fully based on Gutenberg with the support of Roots Sage 10
2022 edition of the inRage Theme fully based on Gutenberg with the support of Roots Sage 10

2022 Edition - inRage theme This version of the theme is compatible with the Full site editing of Wordpress 5.8/5.9 and use Sage 10 in order to manage

Projet Jura2021-2022

CodeIgniter 4 Framework What is CodeIgniter? CodeIgniter is a PHP full-stack web framework that is light, fast, flexible, and secure. More information

Mailing Microservice - My solution for Moroccan PHPers's February 2022 Challenge
Mailing Microservice - My solution for Moroccan PHPers's February 2022 Challenge

Mailing Microservice Solution for Moroccan PHPers's February 2022 Challenge by Rabyâ Raghib ([email protected]). It mainly consists of: a php app th

A&D challenge for AIS3 EOF CTF 2022 Final.

A&D challenge for AIS3 EOF CTF 2022 Final.

Queue Management Systems for LPG vendor agencies of Sri Lanka, for the LPG shortages in 2022

gas-queue-mgt Queue Management Systems for LPG vendor agencies of Sri Lanka, for the LPG shortages in 2022 Installation Requirements PHP 7.4 or later

Trabajo final de la materia Bases de Datos 1. Creación de una base de datos con MySQL y desarrollo de una página web con PHP para manipularla. UNAL sede Medellín, semestre 2022-1.

Trabajo final BD: i-Lunch Materia: Bases de Datos I Profesor: Francisco Javier Moreno Arboleda Institución: Universidad Nacional de Colombia sede Mede

Major Security Vulnerability on PrestaShop Websites - CVE-2022-31101
Major Security Vulnerability on PrestaShop Websites - CVE-2022-31101

Fix Major Security Vulnerability on PrestaShop Websites 🚀 CVE-2022-31101 detector and fixer! A newly found exploit could allow remote attackers to ta

Owner
Julian Scheuchenzuber
Web & Mobile Maniac from Lower Bavaria. Crazy about Typescript, Ionic, Vue, node.js and Silverstripe.
Julian Scheuchenzuber
Silverstripe-searchable - Adds to the default Silverstripe search by adding a custom results controller and allowing properly adding custom data objects and custom fields for searching

SilverStripe Searchable Module UPDATE - Full Text Search This module now uses Full Text Support for MySQL/MariaDB databases in version 3.* Adds more c

ilateral 13 Apr 14, 2022
Silverstripe-masquerade - SilverStripe module to allow users to "masquerade" as other users

SilverStripe Masquerade Module About This module is designed to allow an Administrator to "login" as another "Member" without changing their password

Daniel Hensby 14 Apr 14, 2022
Silverstripe-debugbar/ - SilverStripe DebugBar module

SilverStripe DebugBar module Requirements SilverStripe ^4.0 maximebf/php-debugbar jdorn/sql-formatter Installation You can install the debug bar with

Thomas Portelange 52 Dec 21, 2022
Silverstripe-fulltextsearch - Adds external full text search engine support to SilverStripe

FullTextSearch module Adds support for fulltext search engines like Sphinx and Solr to SilverStripe CMS. Compatible with PHP 7.2 Important notes when

Silverstripe CMS 42 Dec 30, 2022
A SilverStripe module for conveniently injecting JSON-LD metadata into the header of each rendered page in SilverStripe

A SilverStripe module for conveniently injecting JSON-LD metadata into the header of each rendered page in Silver

null 4 Apr 20, 2022
Build lightning-fast and feature-rich websites with ProcessWire.

WIREKIT Core Build lightning-fast and feature-rich websites with ProcessWire. Website: wirekit.dev (in plans) Demo: start.wirekit.dev/core/ Updates: W

Ivan Milincic 10 Nov 3, 2022
⚡️Lightning-fast linter for .env files. Written in Rust 🦀

⚡️ Lightning-fast linter for .env files. Written in Rust ?? Dotenv-linter can check / fix / compare .env files for problems that may cause the applica

null 1.5k Dec 31, 2022
Provides Bitcoin-Lightning payment gateway powered by Strike

Bitcoin Payments - Powered by Strike Drupal module to allow user to pay with bitcoin on your Commerce website using Strike API. Strike Js is used for

Rahul Bile 2 Apr 17, 2022
Lightning Fast, Minimalist PHP User Agent String Parser.

Lightning Fast, Minimalist PHP User Agent String Parser.

Jesse Donat 523 Dec 21, 2022
Sources of Big Pile of Vim-like

Sources of Big Pile of Vim-like The site is a list of Vim-like applications and Vim-emulation plugins. And this repository contains a bit of PHP code

xaizek 14 Dec 14, 2022