SMUI sveltekit Textfield always null on form submit

674 views Asked by At

I've just started using SMUI and sveltekit and I'm running into an issue . . .

I'm using the Textfield component in a login form, and this doesn't work:

<form method="post">
    <Textfield variant="outlined" bind:value={username} label="Username"></Textfield>    
    <Textfield type="password" variant="outlined" bind:value={password} label="Password">
    <Button type="submit">Login</Button>
</form>

Which posts to a page with this code:

export const actions = {
    default: async ({ cookies, request }) => {

        const data = await request.formData()
        const username = data.get('username')
        const password = data.get('password')
    }
}

username and password are both null on submit.

To make this work, I insert "shadow" hidden fields

<form method="post">
    <Textfield variant="outlined" bind:value={username} label="Username"></Textfield>    
    <input type="hidden" name="username" value={username}>
    <Textfield type="password" variant="outlined" bind:value={password} label="Password">
    <input type="hidden" name="password" value={password}>
    <Button type="submit">Login</Button>
</form>

And then I get values for username and password. I'm assuming I don't need to do this - what am I doing wrong?

Edit 2022-10-17 It was suggested that I add a "name" parameter to the textfields like so:

    <Textfield variant="outlined" value="" name="username"></Textfield>
<Textfield type="password" variant="outlined" value="" name="password"></Textfield>

That also doesn't work - when the values come over for the form they are both null.

Other ideas?

3

There are 3 answers

2
Ian Douglas On BEST ANSWER

You can specify the name of the nested input element like so:

<Textfield input$name="username" ... />
2
brunnerh On

Form fields are only submitted if they have a name attribute. The bindings are completely irrelevant, you only need them if you want to use the values elsewhere in the code or component.

0
alexvdvalk On

You can create a normal input field and mark it as hidden, and then set the value with 2 way binding:

    <Select variant="filled" bind:value={selectedUserId} label="User">
      <Option value="" />
      {#each usersList as user}
        <Option value={user.id}>{user.firstName} {user.lastName}</Option>
      {/each}
    </Select>
    <input hidden name="user-select" value={selectedUserId} />