3

I have a dynamic form, I render my components ( input component, textarea components...) depends on what i have in my database table, I would like to know how can i submit the form since i don't know the names of my v-models because each user in my application can make a different form.

<template>
    <b-modal id="modal-1" v-model="showModal" title="Add Contact" modal-class="right" content-class="rounded-0" @ok="handleOk" @hidden="resetModal">
        <form ref="form" name="addcontact">
            <render :definition="response"></render>
        </form>
    </b-modal>
</template>

<script>

import render from "../../components/forms/dynamic-render";

export default {
    components:{
        render
    },
    data() {
        return {
           showModal: true,
           response: [
               {type:'text', label: 'My title', is_required:1},
               {type:'textarea', label: 'text zone'}
           ]
        }
    },
    methods:{
        resetModal: function(){
            this.$emit('close');
        },
        handleSubmit: function($e){
            // i want to submit using axios but I don't know how in this case ( dynamic form with different v-model value ) 
        },
        handleOk: function(bvModalEvt){
            
            this.handleSubmit();
        }
    }
};
</script>
Maik Lowrey
  • 10,972
  • 4
  • 14
  • 43
AiTech
  • 75
  • 6
  • 1
    What about simply serialising the form and submitting its data to whatever endpoint you have? https://stackoverflow.com/questions/11661187/form-serialize-javascript-no-framework – Terry Jan 30 '22 at 16:29

1 Answers1

0

I don't know the names of my v-models because each user in my application can make a different form.

You don't need to know the name. Moreover, You only need the data that the user provides.

The solution that I've provided to you is to get the data from the render component:

1st, You need to bind all the form input, textarea, and select elements to a Json Object

Such as

<template>
  <p>Assume a complex dynamic layout</p>
</template>
<script>
export default {
  name: 'render',
  data () {
    return {
    /* bind all the  input, textarea, and select elements to the Item object */
      Item: {
        foo: 'foo',
        bar: 'bar'
      }
    }
  },
  methods: {
    EnvelopeItem: function () {
      return JSON.stringify(this.Item)
    }
  }
}
</script>

2nd, define a method to have access to the Item from the parent component (EnvelopeItem)

3rd, assign a reference (ref) to the render component

<render ref="render" :definition="response"></render>

4th, call the EnvelopeItem from the parent component via the render reference

handleSubmit: function ($e) {
  let json = this.$refs.render.EnvelopeItem()
  console.log(json)
  // i want to submit using axios but I don't know how in this case ( dynamic form with different v-model value )
}

All done.

A Farmanbar
  • 4,120
  • 5
  • 20
  • 39