-1

I have this form that has a dropdown box. Everything works fine except if you have "Please Select" selected it saves the value of it which is 0 to the database and because of that when I go to the page that displays the product, the page breaks because it can't find the category.

Here is my code

<template>
    <div>
        <select class="form-select form-control" v-model="newCategory">
            <option value="0" selected>Please Select</option
            <option v-for=category in categories" :value=category.id>
                {{ category.name }}
            </option>
        </select>

        <button class="btn btn-success" @click="save">Save</button>
    </div>
</template>

<script>
    export default {
        props: ['categories'],
        data() {
            return {
                newCategory: 0
            }
        },
        methods: {
            save(){
                axios.post('/api/products/create', {
                    category: this.newCategory
                }).then(response => {
                    this.newCategory = 0;
                });
            }
        }
    }
</script>

2 Answers2

0

Just check this.newCategory before you send a request to the server. If it is 0, show a toast or something.

The code should be like this:

save(){
if(this.newCategory === 0) show something and return;
// bottom codes will be shown only in else section
            axios.post('/api/products/create', {
                category: this.newCategory
            }).then(response => {
                this.newCategory = 0;
            });
        }
Ahmed Gad
  • 691
  • 1
  • 7
  • 26
mortezaa
  • 21
  • 2
-1

First you need to make your newCategory field accept null values, because you need to populate it even if you are saving data without selecting option. Then try the following:

<select v-model="newCategory">
  <option value="" disabled selected>Select your option</option>
  <option v-for=category in categories" :value=category.id>
    {{ category.name }}
  </option>
</select>


data() {
 return {
   newCategory: null
 }
},