skip to Main Content

When I add a new movie with the form, I want it to have the category with the id ‘all-films’ by default. How can i do this? Thanks in advance. Here are the codes:

new-film.tsx –>

const form = useForm({
    resolver: zodResolver(formSchema),
    defaultValues: {
        id:"",
        name: "",
        imageUrl: "",
        filmUrl: "",
    }
})

const onSubmit = async (values: z.infer<typeof formSchema>) => {
    try {
        await axios.post("/api/films", values)
        
        form.reset()
        router.refresh()
        onClose()
    } catch (error) {
        console.log(error);
    }
}

api/films/route.ts –>

import { db } from "@/lib/db";
import { NextResponse } from "next/server";

export async function POST(req: Request){
    try {
        const { id, name, imageUrl, filmUrl } = await req.json()

        const film = await db.film.create({
            data: {
                id,
                name,
                imageUrl,
                filmUrl
            }
        })

        return NextResponse.json(film)
    } catch (error) {
        console.log("[GAMES_POST]", error);
        return new NextResponse("Internal Error", {status: 500})
    }
}

schema.prisma –>

model Category {
  id String @id
  name String
  imageUrl String @db.Text

  films Film[]

  createdAt DateTime @default(now())
  updatedAt DateTime @updatedAt
}

model Film {
  id String @id
  name String
  imageUrl String @db.Text
  filmUrl String @db.Text

  category Category[]

  createdAt DateTime @default(now())
  updatedAt DateTime @updatedAt
}

When I add a new movie with the form, I want it to have the category with the id ‘all-films’ by default. How can i do this? Thanks in advance. Here are the codes:

2

Answers


  1. Chosen as BEST ANSWER

    I solved the problem as follows:

        const film = await db.film.create({
            data: {
                id,
                name,
                imageUrl,
                filmUrl,
                category: {
                    connect: { id: 'all-films' }
                }
            }
        })
    

  2. The simplest solution would be to edit your POST-function and at catgory as a new parameter and to fill it:

    const categoryId = "all-films"
    const film = await db.film.create({
      data: {
        id,
        categoryId,
        name,
        imageUrl,
        filmUrl
        }
      })
    

    If you want the user to be able to select a category and just have it pre-filled you need to expand your form and then add a default value (you already have some empty ones it would seem):

    const form = useForm({
        resolver: zodResolver(formSchema),
        defaultValues: {
            id:"",
            categoryId: "all-films",
            name: "",
            imageUrl: "",
            filmUrl: "",
        }
    })
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search