Skip to content

Commit

Permalink
feat: virtual fields example (#1990)
Browse files Browse the repository at this point in the history
  • Loading branch information
JessChowdhury authored Feb 16, 2023
1 parent cfb3632 commit 2af0c04
Show file tree
Hide file tree
Showing 18 changed files with 657 additions and 0 deletions.
3 changes: 3 additions & 0 deletions examples/virtual-fields/.env.example
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
MONGODB_URI=mongodb://localhost/payload-example-virtual-fields
PAYLOAD_SECRET=ENTER-STRING-HERE
PAYLOAD_PUBLIC_SERVER_URL=http://localhost:3000
5 changes: 5 additions & 0 deletions examples/virtual-fields/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
build
dist
node_modules
package-lock.json
.env
1 change: 1 addition & 0 deletions examples/virtual-fields/.npmrc
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
legacy-peer-deps=true
62 changes: 62 additions & 0 deletions examples/virtual-fields/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
# Virtual Fields Example for Payload CMS

This example demonstrates multiple use-cases for virtual fields.

## Getting Started

First copy this example with [Degit](https://www.npmjs.com/package/degit) by running the following command at your terminal:

```bash
npx degit github:payloadcms/payload/examples/virtual-fields
```

1. `cd` into this directory and run `yarn` or `npm install`
2. `cp .env.example .env` to copy the example environment variables
3. `yarn dev` or `npm run dev` to start the server and seed the database
4. `open http://localhost:3000/admin` to access the admin panel
5. Login with email `dev@payloadcms.com` and password `test`


## How It Works

The term *virtual field* is used to describe any field that is not stored in the database and has its value populated within an `afterRead` hook.

In this example you have three collections: Locations, Events and Staff.

#### Locations Collection

In the locations collection, you have separate text fields to input a city, state and country.

Everything else here are virtual fields:

`location`: Text field providing a formatted location name by concatenating `city + state + country` which is then used as the document title

`events`: Relationship field containing all events associated with the location.

`nextEvent`: Relationship field that returns the event with the closest date at this location.

`staff`: Relationship field containing all staff associated with the location.

#### Events Collection

This collection takes an event name and date. You will select the event location from the options you have created in the location collection.

Next we have the Ticket fields, you can input the ticket price, sales tax and additional fees - then our virtual field will calculate the total price for you:

`totalPrice`: Number field that is automatically populated by the sum of `price * tax + fees`

#### Staff Collection

The staff collection contains text fields for a title, first and last name.

Similarly to Events, you will assign a location to the staff member from the options you created previously.

This collection uses the following virtual field to format the staff name fields:

`fullTitle`: Text field providing a formatted name by concatenating `title + firstName + lastName` which is then used as the document title

In the code, navigate to `src/collections` to see how these fields are functioning and read more about `afterRead` hooks [here](https://payloadcms.com/docs/hooks/fields).

## Questions

If you have any issues or questions, reach out to us on [Discord](https://discord.com/invite/r6sCXqVk3v) or start a [GitHub discussion](https://github.com/payloadcms/payload/discussions).
4 changes: 4 additions & 0 deletions examples/virtual-fields/nodemon.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
{
"ext": "ts",
"exec": "ts-node src/server.ts"
}
29 changes: 29 additions & 0 deletions examples/virtual-fields/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
{
"name": "virtual-fields",
"version": "1.0.0",
"main": "dist/server.js",
"license": "MIT",
"scripts": {
"dev": "cross-env PAYLOAD_PUBLIC_SEED=true PAYLOAD_DROP_DATABASE=true PAYLOAD_CONFIG_PATH=src/payload.config.ts nodemon",
"build:payload": "cross-env PAYLOAD_CONFIG_PATH=src/payload.config.ts payload build",
"build:server": "tsc",
"build": "yarn copyfiles && yarn build:payload && yarn build:server",
"serve": "cross-env PAYLOAD_CONFIG_PATH=dist/payload.config.js NODE_ENV=production node dist/server.js",
"copyfiles": "copyfiles -u 1 \"src/**/*.{html,css,scss,ttf,woff,woff2,eot,svg,jpg,png}\" dist/",
"generate:types": "cross-env PAYLOAD_CONFIG_PATH=src/payload.config.ts payload generate:types",
"generate:graphQLSchema": "PAYLOAD_CONFIG_PATH=src/payload.config.ts payload generate:graphQLSchema"
},
"dependencies": {
"dotenv": "^8.2.0",
"express": "^4.17.1",
"payload": "^1.6.11"
},
"devDependencies": {
"@types/express": "^4.17.9",
"copyfiles": "^2.4.1",
"cross-env": "^7.0.3",
"nodemon": "^2.0.6",
"ts-node": "^9.1.1",
"typescript": "^4.8.4"
}
}
91 changes: 91 additions & 0 deletions examples/virtual-fields/src/collections/Events.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,91 @@
import payload from 'payload';
import { CollectionConfig, FieldHook } from 'payload/types';

const getTotalPrice: FieldHook = async ({ data }) => {
const { price, salesTaxPercentage, fees } = data.tickets;
const totalPrice = Math.round(price * (1 + (salesTaxPercentage / 100))) + fees;

return totalPrice;
};

const Events: CollectionConfig = {
slug: 'events',
admin: {
defaultColumns: ['title', 'date', 'location'],
useAsTitle: 'title',
},
fields: [
{
name: 'title',
type: 'text',
required: true,
},
{
type: 'row',
fields: [
{
name: 'date',
type: 'date',
required: true,
},
{
name: 'location',
type: 'relationship',
relationTo: 'locations',
maxDepth: 0,
hasMany: false,
},
],
},
{
name: 'tickets',
type: 'group',
fields: [
{
type: 'row',
fields: [
{
name: 'price',
type: 'number',
admin: {
description: 'USD',
},
},
{
name: 'salesTaxPercentage',
type: 'number',
admin: {
description: '%',
},
},
],
},
{
type: 'row',
fields: [
{
name: 'fees',
type: 'number',
admin: {
description: 'USD',
},
},
{
name: 'totalPrice',
type: 'number',
admin: {
description: 'USD',
readOnly: true,
},
hooks: {
afterRead: [getTotalPrice],
},
},
],
},
],
},
],
};

export default Events;
138 changes: 138 additions & 0 deletions examples/virtual-fields/src/collections/Location.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,138 @@
/* eslint-disable @typescript-eslint/explicit-module-boundary-types */
import payload from 'payload';
import { CollectionConfig, FieldHook } from 'payload/types';

const formatLocation: FieldHook = async ({ data }) => (
`${data.city}${data.state ? `, ${data.state},` : ','} ${data.country}`
);

const getLocationStaff: FieldHook = async ({ data }) => {
const staff = await payload.find({
collection: 'staff',
where: {
location: {
equals: data.id,
},
},
});

if (staff.docs) {
return staff.docs.map((doc) => doc.id);
}

return null;
};

const getNextEvent: FieldHook = async ({ data }) => {
const eventsByDate = await payload.find({
collection: 'events',
sort: 'date',
where: {
location: {
equals: data.id,
},
},
});

if (eventsByDate?.docs) {
return eventsByDate.docs[0]?.id;
}

return null;
};

const getAllEvents: FieldHook = async ({ data }) => {
const allEvents = await payload.find({
collection: 'events',
where: {
location: {
equals: data.id,
},
},
});
if (allEvents.docs) return allEvents.docs.map((doc) => doc.id);

return null;
};

const Locations: CollectionConfig = {
slug: 'locations',
admin: {
defaultColumns: ['location', 'nextEvent'],
useAsTitle: 'location',
},
fields: [
{
name: 'location',
label: false,
type: 'text',
hooks: {
afterRead: [
formatLocation,
],
},
admin: {
hidden: true,
},
},
{
type: 'row',
fields: [
{
name: 'city',
type: 'text',
required: true,
},
{
name: 'state',
type: 'text',
},
{
name: 'country',
type: 'text',
required: true,
},
],
},
{
name: 'events',
maxDepth: 0,
type: 'relationship',
relationTo: 'events',
hasMany: true,
admin: {
readOnly: true,
},
hooks: {
afterRead: [getAllEvents],
},
},
{
name: 'staff',
type: 'relationship',
relationTo: 'staff',
hasMany: true,
maxDepth: 0,
admin: {
readOnly: true,
},
hooks: {
afterRead: [getLocationStaff],
},
},
{
name: 'nextEvent',
type: 'relationship',
relationTo: 'events',
admin: {
position: 'sidebar',
readOnly: true,
},
hooks: {
afterRead: [getNextEvent],
},
},
],
};

export default Locations;
52 changes: 52 additions & 0 deletions examples/virtual-fields/src/collections/Staff.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
import { CollectionConfig, FieldHook } from 'payload/types';

const populateFullTitle: FieldHook = async ({ data }) => (
`${data.title} ${data.firstName} ${data.lastName}`
);

const Staff: CollectionConfig = {
slug: 'staff',
admin: {
defaultColumns: ['fullTitle', 'location'],
useAsTitle: 'fullTitle',
},
fields: [
{
name: 'fullTitle',
type: 'text',
hooks: {
afterRead: [
populateFullTitle,
],
},
admin: {
hidden: true,
},
},
{
name: 'title',
type: 'text',
required: true,
},
{
name: 'firstName',
type: 'text',
required: true,
},
{
name: 'lastName',
type: 'text',
required: true,
},
{
name: 'location',
type: 'relationship',
relationTo: 'locations',
maxDepth: 0,
hasMany: true,
required: true,
},
],
};

export default Staff;
Loading

0 comments on commit 2af0c04

Please sign in to comment.