StartBootstrap / pro-feedback

11 stars 3 forks source link

Form submission issue with material inputs in shadow dom #25

Open matc71 opened 3 years ago

matc71 commented 3 years ago

Hi,

I recently purchased Material Admin Pro theme (with BS5 and material design components) and started testing it in Web environment working with php and native javascript.

Unless i missed something, i'm currently unable to get mdc fields values back on server side when form is submitted, and the material.js script doesn't seem to implement this.

I know this is due to the fact that mdc are encapsulated inside shadow dom and have been looking on the web for some tricks, but i'm still unable to solve this.

Can you provide me with a solution or at least some vanilla javascript to make those shadow dom inputs "submittable" ?

Thanks in advance.

initplatform commented 3 years ago

Hello,

It looks like this is a known issue with material web components

and there is an overarching issue tracking all web components that are extending form inputs

Material Web Components that are designed to work with forms and have all all the basic input capabilities

But as you mention, when using them as plain html and no javascript library, they are not yet behaving as inputs, as the input is hidden in the shadow dom.

No worries! We can get around this.

Here is an example of using some javascript to accomplish what you want, based on the Login example in material-admin-pro: src/pug/pages/app-auth-login-basic.pug

form
    .mb-4
        mwc-textfield#userName.w-100(label='Username', outlined)
    .mb-4
        mwc-textfield#password.w-100(label='Password', outlined, icontrailing='visibility_off', type='password')
    .d-flex.align-items-center
        mwc-formfield#rememberPassword(label='Remember password')
            mwc-checkbox
    .form-group.d-flex.align-items-center.justify-content-between.mt-4.mb-0
        a.small.fw-500.text-decoration-none(href='app-auth-password-basic.html') Forgot Password?
        a.btn.btn-primary(onclick='submitForm()') Login
        script.
            function submitForm() {
                const userName = document.getElementById('userName').value;
                const password = document.getElementById('password').value;
                const rememberPassword = document.getElementById('rememberPassword').value;
                console.log({
                    userName,
                    password,
                    rememberPassword
                });
                // Do some validation
                // Process, or submit for a new page...
            }

I added ids to the mwc elements. I also added a function called submitForm() to the onclick of the Login button.

Inside submitForm you can gather the values and either do validation or submit them. Maybe using window.location with query parameters for a get request, or using fetch.

Hope that helps. Let me know if you hit any other issues.

All the best!

./sam