Skip to content

Commit 1266171

Browse files
committed
Added group checkbox tests
1 parent e7e016f commit 1266171

File tree

3 files changed

+104
-0
lines changed

3 files changed

+104
-0
lines changed
Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
import type { PageServerLoad } from './$types';
2+
import { superValidate } from '$lib/server';
3+
import { schema } from './schema';
4+
import { error } from '@sveltejs/kit';
5+
import type { z } from 'zod';
6+
7+
const groups = [
8+
{
9+
id: 1,
10+
name: 'Group 1',
11+
start_date: new Date(),
12+
end_date: new Date(),
13+
course_id: 10
14+
},
15+
{
16+
id: 2,
17+
name: 'Group 2',
18+
start_date: new Date(),
19+
end_date: new Date(),
20+
course_id: 20
21+
}
22+
];
23+
24+
export const load: PageServerLoad = async () => {
25+
const account: z.infer<typeof schema> = {
26+
27+
name: 'Test',
28+
group: [groups[0]]
29+
};
30+
31+
if (!account) throw error(404);
32+
33+
const form = await superValidate(account, schema);
34+
35+
return { form, groups };
36+
};
Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
<script lang="ts">
2+
import { superForm } from '$lib/client';
3+
import type { PageData } from './$types';
4+
import SuperDebug from '$lib/client/SuperDebug.svelte';
5+
import { schema } from './schema';
6+
import type { z } from 'zod';
7+
8+
export let data: PageData;
9+
10+
type Group = z.infer<typeof schema>['group'] extends (infer U)[]
11+
? U
12+
: never;
13+
14+
const { form, enhance, message, errors } = superForm(data.form, {
15+
validators: schema,
16+
dataType: 'json'
17+
});
18+
19+
function toggleGroup(group: Group, add: boolean) {
20+
form.update(($form) => {
21+
if (add) $form.group.push(group);
22+
else $form.group = $form.group.filter((g) => g.id != group.id);
23+
return $form;
24+
});
25+
}
26+
</script>
27+
28+
<SuperDebug data={$form} />
29+
30+
{#if $message}<h4>{$message}</h4>{/if}
31+
32+
<form method="POST" use:enhance>
33+
{#each data.groups as group (group.id)}
34+
<label>
35+
<input
36+
class="checkbox"
37+
type="checkbox"
38+
checked={!!$form.group.find((g) => g.id == group.id)}
39+
on:click={(e) => toggleGroup(group, e.currentTarget.checked)}
40+
/>
41+
<span>{group.name}</span>
42+
</label>
43+
{/each}
44+
<div>
45+
<button>Submit</button>
46+
</div>
47+
</form>
48+
49+
<style lang="scss">
50+
form {
51+
margin: 2rem 0;
52+
}
53+
</style>
Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
import { z } from 'zod';
2+
3+
export const schema = z.object({
4+
email: z.string().email().nullable(),
5+
name: z.string().nullable(),
6+
group: z
7+
.object({
8+
id: z.number(),
9+
name: z.string(),
10+
start_date: z.date(),
11+
end_date: z.date(),
12+
course_id: z.number()
13+
})
14+
.array()
15+
});

0 commit comments

Comments
 (0)