Generate a dynamic default value for a text field of type String in the Sanity platform

I have a record in Sanity with the following fields: title (string), slug (slug), and path (string).

Is there a way to set up an initialValue for the path field that generates a custom dynamic string based on the value of the slug?

For instance, if the slug value is my-new-path, how can I programmatically set the initialValue of the path field to /blog/events/my-new-path?

export default {
  name: "myPage",
  title: "My Page",
  type: "document",
  fields: [
    {
      name: "title",
      type: "string",
      title: "Page Title",
      validation: (Rule) => Rule.required(),
    },
    {
      name: "slug",
      type: "slug",
      title: "Slug",
      options: {
        source: "title",
        maxLength: 200, // will be ignored if slugify is set
        slugify: (input) =>
          input
            .slice(0, 200)
            .toLowerCase()
            //Remove spaces
            .replace(/\s+/g, "-")
            //Remove special characters
            .replace(/[&\/\\#,+()$~%.'`’":*?<>{}]/g, ""),
      },
      validation: (Rule) => Rule.required(),
    },
    {
      name: "path",
      type: "string",
      title: "URL Path",
      readOnly: true,
    },
  ]
}

Answer №1

To enhance your slug creation process, consider implementing an asynchronous slugifier within your client-side application. This approach involves generating a slug using the async function and patching the document accordingly.

import slugify from 'some-off-the-shelf-slugifier'

async function myAsyncSlugifier(input, schemaType, context) {
  const slug = slugify(input)
  const {document, getClient} = context
  const client = getClient({apiVersion: '2022-12-07'})
  try {
    const patch = await client
      .patch(document._id)
      .set({path: `/foo/bar/${slug}`})
      .commit()
  } catch(e) {
    console.log(e)
  }
 
  
  return slug
}

//…
// schema field
{
  title: 'Slug',
  name: 'slug',
  type: 'slug',
  options: {
    source: 'title',
    slugify: myAsyncSlugifier
  }
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Display a loading bar or prevent any user interface actions until the server has finished generating the file

I am currently developing a force directed layout using d3.js on data retrieved from an MS SQL server database. I'm creating the json file with a python script and running it on a local server using python -m SimpleHTTPServer. My goal is to establish ...

CSS/SCSS/JS: Adjusting header height dynamically while keeping it fixed at the

Check out my Codepen demo here: https://codepen.io/nickfindley/pen/dJqMQW I am seeking to replicate the current behavior of the page without specifying a fixed height for the header. The goal is to make the header adjust dynamically based on the content, ...

Tips on retrieving the API response using AJAX

Currently, I am attempting to retrieve the API response from Flickr using Ajax in my application built with Laravel. To accomplish this, I have established a specific Route and function dedicated to handling API calls. //Route.php Route::post('/getlo ...

Detecting the click area within a window using JavaScript to automatically close an element

Hello everyone, I am currently working on implementing a JavaScript code that is commonly used to detect click areas for closing an element such as a side navigation or a floating division when the user clicks outside of the element. The functionality wo ...

Javascript: struggling with focus loss

Looking for a way to transform a navigation item into a search bar upon clicking, and revert back to its original state when the user clicks elsewhere. The morphing aspect is working correctly but I'm having trouble using 'blur' to trigger t ...

The JavaScript program is occasionally receiving unconventional input

I'm really struggling with this one. As part of a programming exercise, I am developing a JavaScript calculator. You can access the functioning calculator here on Codepen. At the bottom left corner of the calculator interface, you will notice a "+-" ...

How to implement caching for Stripe JS V3 in Next.js with Server-Side Rendering

I am utilizing a getServiceSideProps function to display a complex APP that interacts with an API: const MyApp: NextPage = (props: any) => { let stripePromise: any; const getStripe = async () => { if (!stripePromise) { str ...

Is it possible to replace a server-side templating engine with Angular 2's server-side pre-rendering?

As a novice in web development, I have recently been exploring angular 1.x, react.js, and angular 2 (eventually deciding on angular 2). Lately, I've been intrigued by the concept of server-side pre-rendering. In my understanding, this process is ...

Tips for transferring a variable from Next.js to a plain JavaScript file

When it comes to Canvas Dom operations in my NextJs file, I decided to include a Vanilla JS file using 'next/script'. The code for this is: <Script id="canvasJS" src="/lib/canvas.js" ></Script>. Everything seems to ...

What is the best way to determine the size of the URLs for images stored in an array using JavaScript?

I am working on a project where I need to surround an image with a specific sized 'div' based on the image's dimensions. The images that will be used are stored in an array and I need to extract the height and width of each image before disp ...

Having trouble retrieving a hidden value in JavaScript when dealing with multiple records in a Coldfusion table

In this table, there is a column that allows users to select a predicted time. <cfoutput query="getReservations"> <tbody> <td><input class="form-control predicted" name="predicted" id="ReservaTempoPrevisto" placeholder= ...

Obtain an array containing the keys of an object

How can I retrieve the keys of a JavaScript object as an array, using either jQuery or pure JavaScript? Is there a more concise approach than this? var data = { 'first' : 'apple', 'second' : 'banana' }; var element ...

Creating a dropdown button with three dots in a table row using jQuery

I've been working with tables and I'm trying to create a dropdown list with 3 dots in each table row. I've experimented with a few libraries and custom dropdown options, but none of them seem to be working properly. What I'm looking fo ...

Displaying large state information in React.js

One of my clients provided me with a dataset containing 12,000 records (approximately 20-30MB) and requested that all the data be displayed on one screen without pagination. However, when I load the page and update the component state using an API call, it ...

Using Javascript on the client side to generate fresh images using an image already present on a webpage

Is there a way to slice an image into tiles using JavaScript in a web browser? I want to provide users with the option to choose an image from a gallery on a webpage and then divide that image into 4 or 6 new tiles. The tiles would then be displayed in a ...

Automated user roster refresh

I have an online user list that is dynamically generated using a SQL query on a database table. How can I implement real-time updates to the webpage when a new user logs in? What specific code do I need to include for this functionality? Appreciate any g ...

Performing a file selection in Cypress without the presence of an input element in the DOM

Upon clicking the upload button, a file browser is triggered through the method provided below. To my knowledge, an element is not automatically added to the Document Object Model (DOM) unless explicitly appended to a DOM element. const inputEl = document. ...

Creating a personalized and versatile table component with unique functionality: where to begin?

Looking to create a versatile table component that can adapt for both desktop and mobile versions. If the screen width is below 720px, it should display a table using div, ul, li elements with a "load more" button at the bottom. If the screen width i ...

What is the most effective way to access nested elements by index in JavaScript?

I am looking to design a user-friendly form that presents questions for users to navigate, revealing different answers/questions based on their responses. For example: var json = { "Did you restart the computer?": [ { ...

Please complete and submit the form received from an AJAX request

I am having trouble submitting a form returned by ajax. Below is the code snippet I attempted to use: The file in question is named 3.php <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script> <script> ...