Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Example with react-hook-form #7

Open
cattanr opened this issue Jun 22, 2023 · 8 comments
Open

Example with react-hook-form #7

cattanr opened this issue Jun 22, 2023 · 8 comments

Comments

@cattanr
Copy link

cattanr commented Jun 22, 2023

Hi,
nice work, thank you for the component ! I wanted to use the multiselect inside a form using react-hook-form. I tried to do it with the example from the checkbox component here https://ui.shadcn.com/docs/components/checkbox#:~:text=Submit-,Checkboxes,-Preview but I can't see my value on submit.
Do you have any example of multiselect inside a form ?
Thank you for your help

@mxkaske
Copy link
Owner

mxkaske commented Jun 23, 2023

Hey @cattanr! I'm happy you enjoy the component.
Unfortunately, this is something I haven't done yet - but is on my todo. So maybe I will accelerate and check out how it works with shadcn's Form component.
I keep you informed about it!

@Olivier-OG
Copy link

Hey @mxkaske, I'm also looking into this.
Did you find any insight on how to connect the FormField to the multiselect?

@mxkaske
Copy link
Owner

mxkaske commented Jul 5, 2023

Hey guys!

So I just created a branch feat/multi-select-form that uses a dead simple example of shadcn Form ui.

It's more of a guideline and provides a first functional draft.

  1. Created form directly embedded inside a page.
  2. Updated fancy-multi-select to include the onChange prop that gets called on each selected change (via useEffect.)

preview link (open the console to see on submit trigger)

I hope this helps a bit more!

// @/app/examples/multi-select-form/page.tsx
"use client";

import * as z from "zod";
import { zodResolver } from "@hookform/resolvers/zod";
import { useForm } from "react-hook-form";
import { FancyMultiSelect } from "@/components/craft/fancy-multi-select";
import { Button } from "@/components/ui/button";
import {
  Form,
  FormControl,
  FormDescription,
  FormField,
  FormItem,
  FormLabel,
  FormMessage,
} from "@/components/ui/form";

const formSchema = z.object({
  frameworks: z
    .array(z.string())
    .refine((value) => value.some((item) => item), {
      message: "You have to select at least one item.",
    }),
});

export default function ExampleForm() {
  const form = useForm<z.infer<typeof formSchema>>({
    resolver: zodResolver(formSchema),
    defaultValues: {
      frameworks: [],
    },
  });

  function onSubmit(values: z.infer<typeof formSchema>) {
    // Do something with the form values.
    // ✅ This will be type-safe and validated.
    console.log(values);
  }

  return (
    <main className="container mx-auto flex min-h-screen items-center justify-center">
      <Form {...form}>
        <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-8">
          <FormField
            control={form.control}
            name="frameworks"
            render={({ field }) => (
              <FormItem>
                <FormLabel>Frameworks</FormLabel>
                <FormControl>
                  <FancyMultiSelect
                    onChange={(values) => {
                      field.onChange(values.map(({ value }) => value));
                    }}
                  />
                </FormControl>
                <FormDescription>All the frameworks you like.</FormDescription>
                <FormMessage />
              </FormItem>
            )}
          />
          <Button type="submit">Submit</Button>
        </form>
      </Form>
    </main>
  );
}

@spiritoftime
Copy link

Hello @mxkaske, thank you for taking the time to create a first draft with react hook form! I'm currently also trying to use multiselect via shadcn on a multi page form.
I would like to point out that at feat/multi-select-form fancy-multi-select, selectables is not being filtered out properly and hence my multiselect was allowing repeated selects.

Current:

` const selectables = FRAMEWORKS.filter(
    (framework) => !selected.includes(framework)
  );

I changed it to:

`  const selectables = FRAMEWORKS.filter((framework) => {
    return !selected.some((selectedFramework) => {
      return JSON.stringify(framework) === JSON.stringify(selectedFramework);
    });
  });`

Sandbox: https://codesandbox.io/s/javascript-forked-gldwdt?file=/index.js:854-1075
https://stackoverflow.com/questions/50371188/javascripts-includes-function-not-working-correctly-with-array-of-objects

Thank you so much for this component!
`

@Chr1s0Blood
Copy link

anything about default values?

@SakarDev
Copy link

SakarDev commented Oct 29, 2024

If you're encountering the error undefined is not iterable (cannot read property Symbol(Symbol.iterator)) with cmdk v1.0.0 or later, this is due to a breaking change where Command.List became mandatory.

To fix it you have 2 options:

1- Either Downgrade cmdk to ^0.2.0 (quick fix)

2- Or include Command.List

<CommandList>
  <CommandGroup className="h-full overflow-auto">
      {/* your command items  */}
  </CommandGroup>
</CommandList>

Edit: i prefer the first option (downgrade cmdk) since the 2nd one caused the same error to show up when selecting all the commands and trying to type in the select input (it may be solvable, but I don't have time to investigate right now)

@mxkaske
Copy link
Owner

mxkaske commented Oct 29, 2024

Thanks for sharing your thoughts, @SakarDev! Yes this example is out of date due to the cmdk bump #19.

@websharkdev
Copy link

@Chr1s0Blood I solved the problem with defaultValues ​​something like this. Not ideal (more than sure), but it works in my case

useEffect(() => { if (field.value.length > 0) setSelected(field.value); }, []);
provided that we receive an array with some data - we pass this data to setSelected

By default field.value = [] but if default value field.value = [....] we are gonna set this data to setSelected

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

7 participants