tjinauyeung / svelte-forms-lib

📝. A lightweight library for managing forms in Svelte
https://svelte-forms-lib-sapper-docs.now.sh/
MIT License
604 stars 59 forks source link

Manually modify initialValues #191

Open georgeemr opened 1 year ago

georgeemr commented 1 year ago

Is there a way that I can modify the value of the initialValues when using the helper components? I want to change 3 inputs when one input changes because I want to get from the server the values.

const initialValues = { identification: "", // --> When input, i want to change firstname, lastname, and lastname2 with values from the server firstName: "", lastName1: "", lastName2: "" };

<div class="form-group">
      <label for="identification"
        >Número de identificación<span class="required">*</span></label
      >
      <!-- <input
        on:change={handleIdentificationInput}
        class="form-control"
      /> -->
      <Field name="identification" type="text" class="form-control" />
      <ErrorMessage class="form-error" name="identification" />
    </div>
    <div class="row">
      <div class="col-lg-12">
        <div class="form-group">
          <label for="firstName">Nombre<span class="required">*</span></label>
          <Field
            name="firstName"
            type="text"
            class="form-control"
            disabled={!nombreCustom}
          />
          <ErrorMessage class="form-error" name="firstName" />
        </div>
      </div>
      <div class="col-lg-6">
        <div class="form-group">
          <label for="lastName1">Apellido1<span class="required">*</span></label
          >
          <Field
            name="lastName1"
            type="text"
            class="form-control"
            disabled={!nombreCustom}
          />
          <ErrorMessage class="form-error" name="lastName1" />
        </div>
      </div>
      <div class="col-lg-6">
        <div class="form-group">
          <label for="lastName2">Apellido2<span class="required">*</span></label
          >
          <Field
            name="lastName2"
            type="text"
            class="form-control"
            disabled={!nombreCustom}
          />
          <ErrorMessage class="form-error" name="lastName2" />
        </div>
      </div>
    </div>

I'm unable to call a custom function and change the values directly because the Form don;t detect the change and because of that the form says the value is required.

taronaeo commented 1 year ago

@georgeemr createForm exposes a Svelte writable store named form. In your case, you can use a reactive block to fetch the data from the server when the form changes, and use .update() from the store to update your values.

E.g.,

$: {
  // fetch data from API
  form.update(data => ({ ...data, firstName: API_RESULT_FIRSTNAME, lastName: API_RESULT_LASTNAME, lastName1: API_RESULT_LASTNAME1 }))
}

Edit: specify which Svelte writable store is exposed