Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

partabsaifzakir's avatar

Fetch Data and Populate in Text Boxes if Selected Dropdown Option

QUESTION UPDATED WITH CURRENT STATUS

I'm using Laravel 5.7 & VueJs 2.5.* ...

I want to autofill my form textboxes with the values in database when i select dropdown option. i've been finding solution since days but didn't get any success. I'm very new at this.

WHAT I WANT TO DO:

I have two invoices VendorInvoice and CustomerInvoice, I created my VendorInvoice, fill all data and store in DB. But when i want to create CustomerInvoice, i need to fetch & autofill the same data which i filled and stored in DB for VendorInvoice. So when i create CustomerInvoice, I have a <select> options of VendorInvoice_no, by selecting any option CustomerInvoice form fields should auto fill with the VendorInvoice & VendorInvoiceItems data. So i don’t have to fill same data by myself again in `CustomerInvoi.

In my code:

VendorInvoice = ticketInvoice && VendorInvoiceItems = ticketInvoiceItems

CustomerInvoice = ctInvoice && CustomerInvoiceItems = ctInvoiceItems

If anyone could help to get me out from this issue i'll be very grateful. Thank You.

Here Is my HTML <select> & some ctInvoice & ctInvoiceItems fields which i want to autofill:

    <form @submit.prevent="editmode ? updateCtInvoice() : createCtInvoice()">
      <div class="modal-body">
        <div class="row">

          <!-- =====VENDOR INVOICE SELECTION===== -->
          <select id="ticket_invoice_no" v-model="selectedTicketInvoiceId" @change="getRecord" name="ticket_invoice_no" type="text" class="form-control">
            <option v-for="ticketInvoice in ticketInvoices" :key="ticketInvoice.id" :value="ticketInvoice.id">{{ ticketInvoice.ticket_invoice_no }}</option>
          </select>

          <!-- =====CUSTOMER TICKET INVOICE NUMBER===== -->
          <input v-model="form.ct_invoice_no" type="text" name="ct_invoice_no" class="form-control">

          <!-- =====CUSTOMER TICKET INVOICE ITEMS===== -->
          <tbody>
            <tr v-for="(ctInvoiceItem, key) in form.ctInvoiceItems" :key="key">
              <!--Passenger Name-->
              <td>
                <input v-model="ctInvoiceItem.ct_passenger_name" size="40" type="text" name="ct_passenger_name" class="table-control form-control">
              </td>

              <!--Ticket No.-->
              <td>
                <input v-model="ctInvoiceItem.ct_ticket_no" size="24" type="text" name="ct_ticket_no" class="table-control form-control">
              </td>

              <!--Flight No.-->
              <td>
                <input v-model="ctInvoiceItem.ct_flight_no" size="7" type="text" name="ct_flight_no" class="table-control form-control">
              </td>
          </tbody>

My @change="getRecord" method:

    getRecord: function(e) {
      axios
        .get("api/ticket-invoice/fetch/" + this.selectedTicketInvoiceId)
        .then(({
          data
        }) => {
          console.log(data);
          this.form = data; // assumes the data keys maps directly to the form properties!!
        })
        .catch(error => {
          console.log(error.response);
        });
    }

Route:

Route::get('ticket-invoice/fetch/{ticket_invoice}', 'API\TicketInvoiceController@fetch')->name('ticket-invoice.fetch');

My fetch(){} method:

    public function fetch($id) {
      $ticketInvoices = TicketInvoice::findOrFail($id);

      return response() ->json([
        'id' => '',
        'customer_id' => '',
        'ct_invoice_no' => $ticketInvoices->ticket_invoice_no,
        'ct_invoice_date' => $ticketInvoices->ticket_invoice_date,
        'ct_invoice_fares_total' => $ticketInvoices->ticket_invoice_fares_total,
        'ct_invoice_grand_total' => $ticketInvoices->ticket_invoice_grand_total,
        'ctInvoiceItems' => $ticketInvoices->ticketInvoiceItems->map(function($item) {
          return [
            // get the relevant $item->property for each key below
            'id' => "",
            'ct_invoice_id' => "",
            'ct_passenger_name' => $item->passenger_name,
            'ct_fares' => $item->fares,
            'ct_sub_total' => $item->sub_total
          ];
        }) ->all()
      ]);
    }

My data() in Vue Component:

    data() {
      return {
        editmode: true,
        selectedTicketInvoiceId: false,
        ticketInvoices: {},
        ctInvoices: {},
        customers: null,
        form: new Form({
          id: "",
          customer_id: "",
          ct_invoice_no: "",
          ct_invoice_date: "",
          ct_invoice_fares_total: 0,
          ct_invoice_grand_total: 0,

          ctInvoiceItems: [{
            id: "",
            ct_invoice_id: "",
            ct_passenger_name: "",
            ct_fares: 0,
            ct_sub_total: 0
          }]
        })
      };
    },

When i select option i see in my Vue Component that specific id data fill in my form:. but its not actually fill my input fields with that data, so i could do some changes in the data and finally store it in DB as a customerInvoice.

Vue Dev Tool BEFORE SELECTING OPTION: enter image description here

Vue Dev Tool AFTER SELECTING OPTION: enter image description here

BUT NOT FILLING FIELDS: enter image description here

0 likes
27 replies
tykus's avatar

What exactly is not working for you; it looks like you are not using the response data???

You can use v-model on the <select> element to bind to your component's data:

<select id="ticket_invoice_no" @change="getRecord" name="ticket_invoice_no" v-model="selectedTicketInvoiceId">

Add a property to the component's data:

data () {
    return {
        selectedTicketInvoiceId: false,
        // ... the other properties
    }
}

In your getRecord, you can get rid of the event.target, using the property from the instance instead:

getRecord: function(e) {
    axios
        .get('api/ticket-invoice/' + this.selectedTicketInvoiceId)
        .then(({data})=> {
            this.form = data; // assumes the data keys maps directly to the form properties!!
        })
        .catch(error => {
            console.log(error.response);
        });
},
partabsaifzakir's avatar

@tykus I have two invoices VendorInvoice and CustomerInvoice… I created my VendorInvoice, fill all data and store in DB… But when i want to create CustomerInvoice, i need the same data which i filled and stored in DB for VendorInvoice. So when i create CustomerInvoice, I have a options of VendorInvoice _no, by selecting any option CustomerInvoice form should auto fill with the VendorInvoice & VendorInvoiceItems data. So i don’t have to fill same data by myself again in CustomerInvoice… Thats what i want.... Please help me out.

Image for better understanding: enter image description here

partabsaifzakir's avatar

@tykus i did exactly as u showed me but i'm getting this error in console : Cannot read property 'has' of undefined", also my form is not auto-fill with the selectedinvoiceID data, as i want.

tykus's avatar

Ok. First things first, are you making the request that you expect whenever you change the selection; i.e. a GET request to 'api/ticket-invoice/1234567(a valid id, not the option text)?

If that is working, make sure that you are getting to the controller method - running laravel dump server will allow you to see dump() output without needing to inspect the response. You can add some dump to the controller action:

public function fetch($id) {
    $ticketInvoices = TicketInvoice::findOrFail($id);

    dump($id, $ticketInvoices);

    return $ticketInvoices;
}

...and run the following on your commandline while making a request (i.e. selecting an option:

php artisan dump-server

Once that is confirmed, check that you are receiving the response data as expected in the then callback:

axios
    .get('api/ticket-invoice/' + this.selectedTicketInvoiceId)
    .then(({data})=> {
        console.log(data);
        this.form = data;
    })
    // ...

Lastly, make sure that the keys in the data JSON object map to the same keys in the components form property.

partabsaifzakir's avatar

@tykus

First: when i select option i get like this in my console network: enter image description here

Second: i did this: dump($id, $ticketInvoices); in my fetch(). after running command: php artisan dump-server. When i select option i get TicketInvoice Its Items and all its details. enter image description here

Third: When i did this: console.log(data); after then, i get this in my console after selecting option: enter image description here

partabsaifzakir's avatar

@tykus

I just dont understand this: "Lastly, make sure that the keys in the data JSON object map to the same keys in the components form property."

tykus's avatar

Great.

The first think I see is the difference between the response data and the keys in the component's form property, i.e. very broadly speaking, the response data is ticket_invoice_* while the existing property is ct_invoice_*. So whenever you assign the response data to this.form, you are not modifying the existing keys, but instead replacing with new ones.

You will need to either map the response data keys to the form keys, or change the data keys that comes back from the controller.

Here is an example of how you can return the data in the form that your component needs:

public function fetch($id)
{
    $ticketInvoices = TicketInvoice::findOrFail($id);

    return response()->json([
        'id' => $ticketInvoices->id,
        'customer_id' => '',  // ??? can't see a possible mapping
        'ct_invoice_no' => $ticketInvoices->ticket_invoice_no,
        'ct_invoice_date' => $ticketInvoices->ticket_invoice_date,
        'ct_invoice_fares_total' => $ticketInvoices->ticket_invoice_fares_total,
        'ct_invoice_grand_total' => $ticketInvoices->ticket_invoice_grand_total,
        'ctInvoiceItems' => $ticketInvoices->ticket_invoice_items->map(function ($item) {
            return [
                // get the relevant $item->property for each key below
                'id' => "",
                'ct_invoice_id' => "",
                'ct_passenger_name' => "",
                'ct_fares' => 0,
                'ct_sub_total' => 0
            ];
        })->all();
    ]);
}
partabsaifzakir's avatar

@tykus

Could you show me some code, how to do that, because i don't understand or speak English very well, but maybe i understand code.

I think i'm close, because of you, just need more help to finish this.

One more thing when i select option, i see my Vue dev tool, all the ticketInvoice details fills in form, but data is not actually filling in the fields so i could do some changes in the data and finally store it in DB as a customerInvoice.

Vue Dev Tool BEFORE SELECTING OPTION: enter image description here

Vue Dev Tool AFTER SELECTING OPTION: enter image description here

BUT NOT FILLING FIELDS: enter image description here

tykus's avatar

That is exactly as I described above; your form property now has different keys, and thererfore, cannot populate the elements in the template.

The additional controller code in my last reply will return the data from the controller with the keys matching the existing form property on the Vue component; give that a try, it should work.

tykus's avatar

That particular $ticketInvoice instance has no ticket_invoice_items associated with it. I expected this was an eager-loaded relation (which would have returned an empty Collection, hence map). What is ticket_invoice_items; where does it come from?

partabsaifzakir's avatar

@tykus

A ticketInvoice hasMany ticketInvoiceItems, same forctInvoicehasManyctInvoiceItems` i made a model for both of them and make relation between them.

Here is their models...

ticketInvoice Model: enter image description here

ticketInvoiceItems Model: enter image description here

partabsaifzakir's avatar

@tykus

I did this: $ticketInvoices->ticketInvoiceItems->map(function ($item)

Now i'm not getting error 500, My Vue Dev Tool form is like this after i select options:

enter image description here

Still fields are not filling with data.

tykus's avatar

What does the Vue template look like? How are you mapping the form property to the form in the template?

tykus's avatar

Sure. (The code, not the rendered HTML!)

partabsaifzakir's avatar

@tykus

Here are some <input> fields of ctInvoice & ctInvoiceItems.

<form @submit.prevent="editmode ? updateCtInvoice() : createCtInvoice()">
  <div class="modal-body">
    <div class="row">

      <!-- =====VENDOR INVOICE SELECTION===== -->
      <select id="ticket_invoice_no" v-model="selectedTicketInvoiceId" @change="getRecord" name="ticket_invoice_no" type="text" class="form-control">
        <option v-for="ticketInvoice in ticketInvoices" :key="ticketInvoice.id" :value="ticketInvoice.id">{{ ticketInvoice.ticket_invoice_no }}</option>
      </select>

      <!-- =====CUSTOMER TICKET INVOICE NUMBER===== -->
      <input v-model="form.ct_invoice_no" type="text" name="ct_invoice_no" class="form-control">

      <!-- =====CUSTOMER TICKET INVOICE ITEMS===== -->
      <tbody>
        <tr v-for="(ctInvoiceItem, key) in form.ctInvoiceItems" :key="key">
          <!--Passenger Name-->
          <td>
            <input v-model="ctInvoiceItem.ct_passenger_name" size="40" type="text" name="ct_passenger_name" class="table-control form-control">
          </td>

          <!--Ticket No.-->
          <td>
            <input v-model="ctInvoiceItem.ct_ticket_no" size="24" type="text" name="ct_ticket_no" class="table-control form-control">
          </td>

          <!--Flight No.-->
          <td>
            <input v-model="ctInvoiceItem.ct_flight_no" size="7" type="text" name="ct_flight_no" class="table-control form-control">
          </td>
      </tbody>
tykus's avatar
tykus
Best Answer
Level 104

@partabsaifzakir I have just reread the edited OP, and noticed that the data on the component assigns a new Form to the form key... we were not replicating this when the response was returning from the database:

axios.get('api/ticket-invoice/' + this.selectedTicketInvoiceId)
    .then(({data})=> {
        this.form = new Form(data) 
        // ensure response data match the keys in the component's data.form property
    })
     // ...
1 like
partabsaifzakir's avatar

@tykus Yes! i'm getting the data now

enter image description here

I can now do some changes and save data to the DB now ????

partabsaifzakir's avatar

@tykus

Yes! Everything is working as it should be.....

Where were you before ... ??? I was trying to solve this issue for 7 days......

Please or to participate in this conversation.