solar-forms icon indicating copy to clipboard operation
solar-forms copied to clipboard

Form field validations do not work if nested in other elements or in other components.

Open phillipbaird opened this issue 2 years ago • 1 comments

Thanks for creating this library. While testing I have come across a couple of related issues.

Form fields do not work if nested in other elements

e.g. An input in a div will not be seen by the formGroup function.

<form use:formGroup={fg}>
  <div>
    <input type="email" formControlName="email" />
  <div>
</form>

This was solved by adding a couple of lines to the bottom of the formGroup function to recurse through elements...

export function formGroup<I extends CreateFormGroupInput>(el: Element, formGroupSignal: () => FormGroup<I>) {
  for (const $child of el.children) {
    const formGroupName = getFormGroupName($child);
    if (formGroupName) {
      // Handle nested form groups
      formGroup($child, toNestedFormGroupSignal(formGroupSignal, formGroupName));
    } else {
      const $formControl = getFormControl($child);

      if ($formControl instanceof HTMLInputElement) {
        formGroupForInput($formControl, formGroupSignal);
      } else if ($formControl instanceof HTMLSelectElement) {
        formGroupForSelect($formControl, formGroupSignal);
      } else if ($formControl instanceof HTMLTextAreaElement) {
        formGroupForTextArea($formControl, formGroupSignal);
      } else if ($formControl == null && $child instanceof Element && $child.children.length > 0) {
        // Handle nested elements
        formGroup($child, formGroupSignal);
      }
    }
  }
}

Form fields do not work if nested in custom Solid components.

e.g.

<form use:formGroup={fg}>
    <MyFields />
</form>
function MyFields() {
  return (
    <input type="email" formControlName="email" />
  )
}

Even with the above patch this does not work because formGroup is being used as a directive. It gets executed when the form element is created but before the MyFields elements exist (or at least that's my understanding). I was able to work around this by not using formGroup as a directive but instead calling it from onMount with a ref to the form.

let formRef;

onMount(() => {
  formGroup(formRef, () => fg)
})

return (
  <form ref={formRef}>
    <MyFields />
  </form>
)

Maybe worth mentioning in the docs if there isn't a better solution?

phillipbaird avatar Aug 16 '22 05:08 phillipbaird

I was just about to post a similar issue. Had a working form, but started to wrap my pairs in divs to apply styling. Form breaks. Validation doesn't work and values of inputs just show as blank. This seems like odd behavior to me as wrapping these elements in a div is a pretty standard practice.

spetz83 avatar Dec 22 '22 03:12 spetz83