Dynamic generate date timeIntervals

default discord avatar
martin.rahbeklast year
8

Hello everyone!



How can I dynamically generate time intervals for the "theDate" field, aligning with the value of the "interval" field? I would like the available time intervals to be determined based on the chosen interval duration. Any suggestions or approaches for achieving this dynamically?



  {
    name: "interval",
    type: "number",
    defaultValue: 60,
  },
  {
    name: "theDate",
    type: "date",

    admin: {
      date: {
        displayFormat: "H:mm",
        timeFormat: "H:mm",
        pickerAppearance: "timeOnly",
        timeIntervals: how to make this equals the interval field dynamically?
      },
    },
  },
  • default discord avatar
    paulpopuslast year

    In this case I think the timeIntervals prop is just for the initial render



    Without a PR to change this in core, your best bet is using a custom react component where you can use the React hooks available to listen to other field's value changes



    https://payloadcms.com/docs/fields/overview#custom-components


    https://payloadcms.com/docs/admin/hooks#usefield


    Although I do think it would be useful if these configs could be dynamically set across the board

  • default discord avatar
    martin.rahbeklast year

    Somthing like this?



    import React from "react";
    
    import Date from "payload/dist/admin/components/elements/DatePicker";
    import { Label } from "payload/components/forms";
    import { useField, useFormFields } from "payload/components/forms";
    
    /**
     * A custom DatePicker component with dynamic duration option
     * @constructor
     */
    export const DatePicker: React.FC = (props: any) => {
      const { path, label, required } = props;
      const { value, setValue } = useField({
        path: path,
      });
    
      const duration = useFormFields(([fields, dispatch]) => fields.duration); // should use custom value
    
      if (typeof duration?.value !== "undefined") {
        return (
          <div>
            <Label htmlFor={props.path} label={label} required={required} />
            <Date
              key={props.path}
              {...props.admin.date}
              onChange={(e) => setValue(e)} // TODO: format ???
              value={value}
              timeIntervals={duration?.value || 30}
            />
          </div>
        );
      }
    
      return null;
    };
  • default discord avatar
    paulpopuslast year

    I haven't run it but it looks about right!

  • default discord avatar
    martin.rahbeklast year

    Thanks!

Star on GitHub

Star

Chat on Discord

Discord

online

Can't find what you're looking for?

Get help straight from the Payload team with an Enterprise License.