Appfarm Documentation
Getting startedDocumentationCommunityAppfarm Create
  • Overview
  • Getting Started
    • What is Appfarm?
    • Key concepts
    • Quickstart
      • Speed intro
      • Step-by-step guide
    • Appfarm Showroom
    • FAQ
  • Appcademy
    • Learning paths
    • Appfarm Fundamentals
      • Intro Course
        • 1. Intro to No-Code and Appfarm
        • 2. Navigation in Appfarm Create
        • 3. What is Apps?
        • 4. Intro to UI Editor
        • 5. Data Model
        • 6. App Data
        • 7. Actions
        • 8. Tips and Tricks
        • 9. Intro to practical walkthrough
        • 10. Create a details view of a Project
        • 11. Create a Custom List
        • 12. Swipe and Delete
        • 13. Functionality for simple Create of Data
        • 14. Upload and Download Photos
        • 15. Input Dialog with Validation and Save
        • 16. Dashboard
        • 17. Summary
        • Quiz
      • User Interface Fundamentals
        • Container - Sectioning, Styling and Repeating
        • Conditional Styles
        • Motions
        • Responsive Design
        • Step-by-step workflow
        • Featured UI Components
        • Quiz
      • App Data Fundamentals
        • Data Source Filtering
        • App Variables and Runtime Properties
        • URL Parameters
        • Quiz
      • Actions & Logic Fundamentals
        • Event Handlers
        • Featured Action Nodes
        • Context Parameters
        • Quiz
      • Services Fundamentals
        • Introduction to Services
        • Setting up a Service
        • Scheduling a Service
      • Integration Fundamentals
        • The web request action node
        • Fetch data from an endpoint
        • Map data to a data source
        • Modify the response
        • Nested data mapping
        • Path parameters
        • Authentication
        • Send data to an endpoint
        • Quiz
      • User handling and permissions
        • Users and roles
        • Permissions
        • Creating users
        • Extending the User object class
        • Updating and deleting users
        • Unauthenticated access
        • Quiz
    • Appfarm Professional
      • User Interfaces
        • Featured UI Components
        • Concepts and Use Cases
      • Data Structures & Data Handling
        • Data Features
        • Search & Filters
        • Featured Action Nodes
        • GraphQL
      • Logic & Flow
        • Logical Concepts
        • Date and Time Handling
        • Featured Action Nodes
        • Exception Handling
      • Login & Configuration
        • Login and Authentication
        • Settings, Configuration and Languages
      • Security & Operations
        • Security and Permissions
        • Deployment
        • Schedules and Logs
        • Debugging and App Health
      • Performance & Optimization
        • Optimizing Performance
        • Enhancing Functionality
    • Appfarm Sales Representative
    • Appfarm Developer Forum
      • Session 1: Data Modeling in Appfarm Create
      • Session 2: App Data in Appfarm Create
      • Session 3: Services in Appfarm Create
      • Session 4: Optimizing Performance
    • Background
      • Databases
        • Data modeling 101
        • Database normalization
  • Library
    • UI components
      • Advanced bar chart
      • Advanced bubble chart
      • Advanced combined chart
      • Advanced gantt chart
      • Advanced heatmap chart
      • Advanced line/area chart
      • Advanced pie chart
      • Advanced scatter plot chart
      • Advanced solid gauge chart
      • Animated component
      • Avatar
      • Avatar group
      • Basic bar chart
      • Basic gauge chart
      • Basic line chart
      • Basic pie chart
      • Bottom navigation
      • Button
      • Checkbox
      • Chip group
      • Circular progress
      • Coded component
      • Container
      • Date & time picker
      • Drawable canvas
      • Floating action button
      • Icon
      • Icon button
      • Iframe
      • Image
      • Linear progress
      • List
      • Map
      • Menu list
      • Multi select
      • PDF reader
      • Popover
      • Radio buttons
      • Rich text editor
      • Rich text
      • Select
      • Slider
      • Speed dial
      • Switch
      • Table
      • Tabs
      • Text
      • Text edit
      • View container
      • Visibility group
    • Action nodes
      • Aggregate data
      • Advanced search
      • Auth operations
      • Block
      • Catch exception
      • Copy to clipboard
      • Create file archive
      • Create file object
      • Create object
      • Create user account
      • Delete objects
      • Delete user account
      • Duplicate objects
      • End execution
      • Exit block
      • Exit loop
      • Export data
      • Foreach
      • Generate document
      • If
      • Import data
      • Invalidate cache
      • Log in
      • Log to console
      • Log out
      • Next iteration
      • Navigate
      • Open/close popover
      • Open confirm dialog
      • Open print dialog
      • Open snackbar
      • Open Unsplash dialog
      • Open URL
      • Persist objects
      • Push notifications
      • Read objects
      • Request permissions
      • Run code
      • Run other action
      • Run service
      • Scan barcode/QR code
      • Send email
      • Send SMS
      • Set client language
      • Set data source attributes
      • Set selection
      • Set theme
      • Set user account image
      • Show install app prompt
      • Sleep
      • Sort objects
      • Throw exception
      • Toggle drawer
      • Update object
      • Update secret
      • Update user account
      • Web request
      • While
  • Reference
    • Appfarm Create
      • Appfarm Commander
      • Blue dots
      • Copy & Paste
      • Farmer's Market
      • Find references
      • Find usage
      • Keyboard shortcuts
      • Undo/Redo
      • User preferences
    • Platform concepts
      • Conditions
      • Data bindings
      • Date and time
      • Event handlers
      • Filters
      • Functions
      • Markdown
      • Objects
      • Operators
      • Value processor
    • Dashboard
    • Apps
      • UI
        • Views
          • Dialog
          • Drawer
        • Layout designer
        • Component properties
        • Shareable UI components
      • Data
        • App variables
        • Data sources
        • Calendar data sources
      • Actions
      • App settings
      • App size
      • App health
    • Services
      • Service Endpoints
      • Service settings
      • Service health
      • API explorer
    • Data model
      • Object classes
      • Object class properties
      • Enumerated types
      • GraphQL
        • Queries
        • Mutations
      • Data Extract API
      • Time series data
    • Operations
      • Deploy
      • Schedules
      • Logs
    • Resources
      • Themes
      • Files
      • Fonts
      • Internationalization
    • Configuration
      • Environments
      • Login
        • Custom auth providers
    • Security
      • Users
      • Service accounts
      • Roles
      • Secrets
      • Permissions
        • Conditional Permissions
    • Appfarm Client
      • Developer tools for Apps
      • Developer tools for Services
      • Warnings and errors
  • How to
    • Data modeling
      • Many-to-many relationships
      • Use naming conventions
      • Offline data handling
      • Data silos and White labelling
    • User interface
      • Manage a many-to-many relationship with a Chip group
      • Configure drag and drop
      • Build a drag-and-drop calendar
      • Design a responsive layout
      • Work with flexbox
      • Use Mapbox as a map layer
      • Understand charts
    • Logic and flow
      • Event Log Design
      • Configure advanced search
    • Themes and styling
      • Change the active theme
      • Add custom email templates
    • Enhance your app
      • Add deep links
      • Add keyboard shortcuts
      • Add link previews for social media
      • Apply SEO best practices
      • Change the active language
      • Generate a PDF from a Container
    • Integrations
      • Integrate with external systems
      • Integrate with OpenAI
      • Integrate with Google Analytics (GA4)
      • Configure a custom email account
      • Integrate with a payment provider
      • Integrate with Signicat
      • Integrate directly with an external database
      • Retrieve a Bearer token from Google Cloud
      • Fetch data from BigQuery
      • Retrieve access token from Microsoft Entra ID
    • Workflow automation
      • Update an OAuth 2.0 access token from a service
    • Authentication and access control
      • Add users and assign roles
      • Configure unauthenticated access
      • Implement third-party authentication
    • Security, testing and deployment
      • Add a custom domain
      • Install an app on a device
      • Get ready for Production
      • Optimize performance
      • Security checklist
      • Test and debug
    • Example apps
      • Create an Instagram clone
        • The end result
        • Designing the feed
        • Create new post
        • Add a like-button
        • Add comment-functionality
  • Solution administration
    • Subscription and billing
    • Dedicated tier benefits
    • Guide to GDPR
      • Key principles
      • How Appfarm protects personal data
      • How you can protect your clients’ data
      • Glossary
    • Appfarm and the EU AI Act
  • Policies
    • Appfarm Policies
    • Data Processors
    • Privacy Policy
Powered by GitBook
On this page
  • Properties of the Coded Component
  • Element ID
  • HTML Content
  • Script
  • Calling Actions
  • Integrating with data
  • Resources
  • Namespace
  • Data
  • Actions
  • Content security

Was this helpful?

Export as PDF
  1. Library
  2. UI components

Coded component

PreviousCircular progressNextContainer

Last updated 9 months ago

Was this helpful?

Coded Component enables you to create custom, interactive UI components while still retaining access to your data model. A component can optionally leverage external libraries.

Coded Component is an advanced feature that requires knowledge of JavaScript. It should be considered as a fallback option when a particular component cannot be satisfactorily built using the standard components within Appfarm Create.

Typical use cases include implementing interactive components such as maps, audio/video playback, and 3D viewers, or integrating third-party widgets where using an Iframe is undesirable.

Coded Component examples are available in our . You may view the demos and access the setup in Appfarm Create. If you do not have access, you may register .

Properties of the Coded Component

Element ID

A unique ID for the DOM element containing the coded component. This ID can also be used to link directly to the element on the page.

HTML Content

HTML that will be included inside the coded component HTML element. You should not include DOCTYPE declarations and headers, as these are automatically handled by Create and might create conflicts. Content in script tags will not be run. If you have scripts, these should be placed in the section, whereas links to external scripts should be placed as Script URL in the section.

All the HTML in the coded component is placed in a div when running in your app. Therefore, DOCTYPE declarations and headers might conflict with other elements in your app.

Script

JavaScript to be executed by the coded component. You can access exposed , , and DOM elements within your script through the defined . <script> tags should be omitted.

You cannot use import statements in your JavaScript code. Instead, external libraries should be added as external to the coded component. Most packages will add functions to the global scope, and these can be accessed inside the script section. However, you might get a warning that the package you’re using is undefined. This is a false positive and can be ignored. If you’re adding multiple packages with dependencies on each other, make sure that they are being loaded in the correct order.

const { data: { level, play }, element } = appfarm

const canvas = element.querySelector('canvas')

const src = 'https://storage.googleapis.com/dev-appfarm-public/' 
const stateMachineName = 'State Machine'

const r = new rive.Rive({ // Create will throw a false positive about Rive being undefined 
    canvas, 
    src, 
    autoplay: true, 
    stateMachines: stateMachineName, 
    layout: new rive.Layout({ 
        fit: rive.Fit.Cover, 
        alignment: rive.Alignment.Center, 
    }), 
    onload: (...args) => {
        const inputs = r.stateMachineInputs(stateMachineName);
        
        play.on('change', (val) => {
            if (val) {
                r.play()
            } else {
                r.pause()
            }
        })
        
        level.on('change', (val) => {
            inputs[0].value = val
        })
        
        inputs[0].value = level.get()
    },
});

Calling Actions

Invoking an action returns a Promise, which will be resolved when the action is finished.

appfarm.actions.sendNotification()
    .then(() => console.log('done!'))
    .catch(console.error)

For actions with parameters, specify an object as a function parameter when you invoke the action. This object should contain key/value pairs where the key is the name of the code function param and the value is the value you wish to pass to the action.

// Executing action "Update Animal" with 2 action params from a Script
appfarm.actions.updateAnimal({
    id: '6262a41f6bf4df7b3d7bfe02',
    age: 10
});

Integrating with data

Data Source

Both database-connected and runtime data sources can be connected to a coded component.

A single-cardinality data source will be returned as an object, while a many-cardinality data source will be returned as an array of objects

No method is provided to update objects in data sources. To do that, you should connect an action, using action params to pass values if required.

.get()

Return the object(s).

let species = appfarm.data.animals.get();

.on('change', handler)

Single-cardinality data source:

appfarm.data.tree.on('change', (data) => {  
    console.log(data);
    // {"_id":"6290c8bd4cd17a5bee0bf08b", commonName: "London plane"}
})  

Many-cardinality data source:

appfarm.data.animals.on('change', (data) => {  
    console.log(data);
    // [{"_id":"6262a41f6bf4df7b3d7bfe02", name: "Terrence", ...}, {...}, {...}]
})  

Value

A value can be any individual property from your data model, such as an app variable, resource file, or data source property.

The examples below are for a value of type String with the name species within the default namespace appfarm.

.get()

Return the current value.

let species = appfarm.data.species.get();

.set(value)

Update the value.

appfarm.data.species.set('Enteroctopus dofleini');

.on('change', handler)

React to a change in the value. The change can occur within the script, or elsewhere in your solution.

appfarm.data.species.on('change', (val) => {
    console.log(val);
    // Enteroctopus dofleini
})

Resources

External JavaScript and CSS resources that you want to make available to the coded component. These resources can be embedded (Script, Stylesheet) or linked (Script URL, Stylesheet URL). Custom attributes can be added per resource, and these are included in the script/link tag that is generated. Please make sure that all Script URLs and Stylesheet URLs are accessible, as they can lead to failure to execute the script if they are not available.

Best practice

Namespace

The name of the namespace exposed to the script. Defaults to "appfarm".

The namespace exposes:

  • The DOM element: appfarm.element

Additionally, an event will be emitted on the namespace when the coded component is unloaded.

appfarm.on('unload', () => {  
    // Perform clean-up
})  

Data

Name

A unique name for the data item. Required.

Value Type

The type of value for this data item. Either Data Source , Value or Read-Only Value .

Select Data Source to make an entire data source available, either as an object (single cardinality) or as an array of objects (many cardinality).

Select Value to make a distinct value available. Read-Only Value is similar to Value, but as the name states, it may only be read - not modified from within the script.

Data Source/Value

The data source or value to expose.

Selection

Apply a selection if you have chosen a many cardinality data source above.

  • All objects (default)

  • Selected object(s)

  • Object in context

  • Filtered selection

Description

A description of the data for internal reference.

Here are some examples of how to retrieve and listen to the data available to your coded component.

// Listen to a change in the value
appfarm.data.value.on("change", (val) => {
    // Do something with the newly changed value here
})

// Retrieve the value of a readOnlyValue
appfarm.data.readOnlyValue.get()

// Get all elements that are selected in the data source
appfarm.data.dataSource.get().find(el => el.__SELECTED__ === true); 

Actions

Function Name

A unique name for the function. Required.

Action

The action to expose. If the action has parameters, these can be passed in by the script by specifying the parameter as a Code Function Param. The code function param will get a default name, but this can be edited.

Content security

To access DOM elements, use <namespace>.element. This will let you access the HTML elements that you have defined in the through regular JavaScript. You do not need to wait for the DOM to load before executing your script; Appfarm will automatically handle the timing of the DOM and Script.

In this example, we use Rive.js for interactive motion graphics. Rive.js has been added as a Script URL to the Coded Component in the section. Rive.js adds rive to the global scope, and can be used as such in the Coded Component. Furthermore, we add the following to the section:

<canvas style="width: 100%; height: 100%;"></canvas> And the following javascript to the section.

You can trigger actions from within the script of a coded component, and optionally pass in action parameters. See below for information on how to configure what actions you want to be available from within the script.

Within the property of the coded component, the connected actions are made available within an actions object in the specified . You may invoke an action with the syntax <namespace>.actions.<action_name>().

To execute actions in sequence safely, see the .

You can access your solution's data model within the script of a coded component by connecting data sources and individual values. See the section below for information on how to configure the connection.

Within the property of the coded component, the connected data items are made available within an data object in the specified . Methods are provided to get and set values, as well as react to value changes.

Follow the instructions under to ensure the client can load any externally hosted resources.

CSS added within the Coded Component is applied to the entire document, including the . To avoid unexpected changes to other components, you should prefix your selectors with an according to the Coded Component's Element ID.

: appfarm.data

: appfarm.actions

This is where you add Data Sources to be used inside the Script of your Coded Component. You may add Data Sources or Values (e.g. a property of an object in a data source, or an App Variable). For how to use the data sources and values added in the Data section from within a script, see the section above.

Note that you should not use a coded component to write to a data source. For this purpose, you should use an with action params to handle the updating of any objects.

Actions in your app that should be exposed to the script via a function. For how to trigger the Actions added in the Action section from within a script, see the section above.

By default, Appfarm implements strict content security settings to protect users against common attacks. If you are referencing resources hosted on external domains, you will need to specify those domains within Script Sources or Style Sources under Content Security within a given .

Depending on how your component is implemented, you may also need to specify domains under Web Request Targets and Image Sources. For example, use of the Mapbox GL JS library will require that their domain is whitelisted for both of these content types to load a map successfully.

MDN guide on Promise composition
Developer tools
ID selector
environment configuration
https://api.mapbox.com
Showroom
here
Script
Resources
data
actions
namespace
resources
HTML Content
Script
Actions
Script
namespace
Data
Script
namespace
Content security
Data
Actions
Integrating with data
Action
Calling Actions
Resources
HTML Content