Show Cities according to the selected State

Viewed 67

I'm new on working with Vuetify and Laravel, and I'm facing an issue on conditionally render the Cities according to the selected State. I only want to show the Cities of the selected State, but it's always rendering the cities from all the States. The functions bellow are called after selecting a State (Estado) and City (Cidade), respectively.

    data () {
  return {
    salvando: false,
    loading: true,
    maskCpf: '##.###.###/####-##',
    maskTelRes: '(##) ####-####',
    maskCep: '#####-###',
    emailRules: [v => /.+@.+/.test(v) || 'E-mail invalido'],
    requiredRules: [v => !!v || '* Obrigatório'],
    valid: null,
    disableCidade: '',
    primeiroAcesso: '',
    btnNome: !this.$route.params.codAgroindustria ? 'Salvar' : 'Salvar Alterações',
    form: {
      codAgroindustria: null, // codigo da agroindústria
      NomeFantasia: '',
      RazaoSocial: '',
      Porte: '',
      Cnpj: '',
      estado: '',
      CodEstado: '',
      cidade: '',
      Logradouro: '',
      Numero: '',
      Bairro: '',
      Complemento: '',
      Cep: '',
      TelRes: '',
      email: '',
      // captacao: '',
      // fornecedores: '',
    },
    estado: [{ nome: 'Carregando', id: 0 }],
    cidade: [{ nome: 'Carregando', id: 0 }],
    cadastro: this.$route.params.codAgroindustria === 0 ? 1 : 0,
  }
},
created () {
  // console.log(this.$route.params.codAgroindustria)
  if (this.$route.params.codAgroindustria === undefined) {
    // console.log('Indefinido')
    this.$router.push({ name: 'Listar Agroindustrias' })
  } else if (this.$route.params.codAgroindustria !== 0) {
    // console.log('edicao')
    this.form.codAgroindustria = this.$route.params.codAgroindustria
    this.formDados()
  } else {
    // console.log('cadastro')
    this.loadNewForm()
  }
},
methods: {
  loadNewForm () {
    if (this.$route.params.NomeFantasia !== 'undefined') {
      this.form.NomeFantasia = this.$route.params.NomeFantasia
    }
    if (this.$route.params.Cnpj !== 'undefined') {
      this.form.Cnpj = this.$route.params.Cnpj
    }
    if (this.$route.params.primeiroAcesso === 1) {
      this.primeiroAcesso = 1
    } else {
      this.primeiroAcesso = 0
    }
    this.loading = false
    this.loadEstado()
  },
  updateProfile () {
    this.$refs.form.validate()
    if (!this.valid) {
      this.Swal.fire('Atenção', 'Preencha os itens obrigatórios sinalizados com ("*").', 'warning')
    } else {
      this.salvando = true
      if (this.form.codAgroindustria) { // ATUALIZAR DADOS AGROINDUSTRIA
        this.alert = false
        this.api.put('/agroindustria/attAgroindustria', this.form)
          .then(response => {
            this.salvando = false
            if (response.data.error) {
              let erros = ''
              response.data.message.forEach((el) => {
                erros += el + '<br/>'
              })
              this.Swal.fire({
                title: 'Corrija os erros abaixo:',
                icon: 'warning',
                html: erros,
              })
            } else {
              this.Swal.fire('Sucesso', 'Cadastro Realizado', 'success')
              this.$router.push({ name: 'Listar Agroindustrias' })
            }
          }).catch(error => {
            this.salvando = false
            this.Swal.fire({
              title: 'Atenção:',
              icon: 'warning',
              html: error,
            })
          })
      } else { // CRIAR NOVA AGROINDUSTRIA
        console.log(this.form)
        this.api.post('/agroindustria/createAgroindustria', this.form, this.primeiroAcesso)
          .then(response => {
            this.salvando = false
            if (response.data.error) {
              let erros = ''
              response.data.message.forEach((el) => {
                erros += el + '<br/>'
              })
              this.Swal.fire({
                title: 'Corrija os erros abaixo:',
                icon: 'warning',
                html: erros,
              })
            } else {
              this.Swal.fire('Sucesso', 'Cadastro Realizado.', 'success')
              this.$router.push({ name: 'Listar Agroindustrias' })
            }
          }).catch(error => {
            console.log(error)
            this.salvando = false
            this.Swal.fire({
              title: 'Atenção:',
              icon: 'warning',
              html: error + '<br/>Algo de errado não está certo.',
            })
          })
      }
    }
  },
  formDados () {
    this.api('/agroindustria/', {
      params: {
        codAgroindustria: this.form.codAgroindustria,
      },
    })
      .then(response => {
        this.form.NomeFantasia = response.data[0].NomeFantasia
        this.form.RazaoSocial = response.data[0].RazaoSocial
        this.form.Porte = response.data[0].Porte
        this.form.Cnpj = response.data[0].Cnpj
        this.form.estado = response.data[0].estado
        this.form.CodEstado = response.data[0].estado.CodEstado
        this.form.cidade = response.data[0].cidade
        this.form.Logradouro = response.data[0].Logradouro
        this.form.Numero = response.data[0].Numero
        this.form.Bairro = response.data[0].Bairro
        this.form.Cep = response.data[0].Cep
        this.form.Complemento = response.data[0].Complemento
        this.form.TelRes = response.data[0].TelRes
        this.form.email = response.data[0].email
        this.loadEstadoEdit(response.data[0].estado, response.data[0].cidade)
      }).catch(error => {
        this.message = error
        // console.log(this.message)
      })
  },
  formTelefone (TelRes) {
    for (let i = 0; i < TelRes.length; i++) {
      switch (TelRes[i].CodTipoTelefone) {
        case '1':
          this.form.telCel = TelRes[i].DDD ? '' + TelRes[i].DDD + TelRes[i].Numero : null
          break
        case '2':
          this.form.telCome = TelRes[i].DDD ? '' + TelRes[i].DDD + TelRes[i].Numero : null
          break
        default:
          this.form.telReca = TelRes[i].DDD ? '' + TelRes[i].DDD + TelRes[i].Numero : null
          break
      }
    }
  },
  loadEstado () {
    this.api('/estado').then(response => {
      // console.log(this.response.data.estado)
      this.estado = response.data.estado.map(el => el.Nome)
    }).catch(error => {
      this.message = error
      // console.log(this.message)
    })
  },
  loadCidade (CodEstado) {
    this.api('/cidade', {
      params: {
        CodEstado: CodEstado,
      },
    })
      .then(response => {
        this.cidade = response.data.cidade.map(el => el.Nome)
        this.disableCidade = false
        // console.log(this.cidade)
      }).catch(error => {
        this.message = error
      // console.log(this.message)
      })
  },
  loadEstadoEdit (CodEstado, CodCidade) {
    this.api('/estado').then(response => {
      this.estado = response.data.estado
      this.form.estado = this.estado
      this.form.CodEstado = this.estado.CodEstado
      this.form.estado = this.form.estado[CodEstado - 1]
      this.loadCidadeEdit(CodCidade)
      // console.log(response)
    }).catch(error => {
      this.message = error
      // console.log(this.message)
    })
  },
  loadCidadeEdit (CodCidade) {
    this.api('/cidade').then(response => {
      this.cidade = response.data.cidade
      this.form.cidade = this.cidade[CodCidade - 1]
      this.disableCidade = false
      this.loading = false
      // console.log(response.data.cidade)
    }).catch(error => {
      this.message = error
      // console.log(this.message)
    })
  },
  changeCidade () {
    console.log(this.form.estado)
    this.loadCidade(this.form.estado.CodEstado)
    // console.log(this.company.estado)
  },
},

}

As you can see, I tried to show the cities that has the same CodEstado parameter of the selected State.

Thank you in advance.

CidadeController.php:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Cidade;

    class CidadeController extends Controller
    {
    
        public function getCidadesByEstado (Request $request)
        {
            $CodEstado = $request->get('CodEstado');
    
            if ($CodEstado == '') {
                $cidade = Cidade::all();
            } else {
                $cidade = Cidade::where('CodEstado', $CodEstado)
                ->orderBy('nome', 'asc')
                ->get();
            }
    
            return response()->json([
                'error' => false,
                'cidade' => $cidade
            ]);
        }
    
    }

EstadoController.php <?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Estado;

class EstadoController extends Controller
{

    public function getEstado()
    {
        $estado = Estado::all();

        return response()->json([
            'error' => false,
            'estado' => $estado
        ]);
    }

}

My Vuetify code for the FrontEnd:

<template>
  <v-card
    class="ma-3"
  >
    <div class="content">
      <template>
        <v-card
          :class="{ 'card-success': cadastro, 'card-warn': !cadastro}"
          style="min-height: 60vh"
        >
          <h4
            v-if="!cadastro"
            slot="header"
            class="card-title text-center"
          >
            Edição de Agroindústria
          </h4>
          <h4
            v-else
            slot="header"
            class="card-title text-center"
          >
            Cadastro de Agroindústria
          </h4>
          <div class="clearfix" />
          <div
            v-if="loading"
            style="height: 60vh"
          >
            <v-row
              class="fill-height ma-2 flex-column"
              align="center"
              justify="center"
            >
              <v-progress-circular
                :size="70"
                color="primary"
                indeterminate
              />
            </v-row>
          </div>
          <div v-if="!loading">
            <v-form
              id="form"
              ref="form"
              v-model="valid"
              class="pa-3"
              lazy-validation
              @submit.prevent="updateProfile"
            >
              <v-card>
                <v-list-item-content>
                  <v-card-title
                    class="headline mx-auto"
                  >
                    Dados Pessoais
                  </v-card-title>
                  <v-row
                    v-if="!loading"
                    class="pa-3"
                  >
                    <!-- <v-col
                      cols="12"
                    >
                      <v-text-field
                        v-model="form.Nome"
                        label="Nome *"
                        :rules="requiredRules"
                      />
                    </v-col> -->
                    <v-col
                      cols="6"
                    >
                      <v-text-field
                        v-model="form.NomeFantasia"
                        label="Nome Fantasia *"
                        :rules="requiredRules"
                      />
                    </v-col>
                    <v-col
                      cols="6"
                    >
                      <v-text-field
                        v-model="form.RazaoSocial"
                        label="Razão Social *"
                        :rules="requiredRules"
                      />
                    </v-col>
                    <v-col
                      cols="6"
                    >
                      <v-text-field
                        v-model="form.Porte"
                        label="Porte *"
                        :rules="requiredRules"
                      />
                    </v-col>
                    <v-col
                      cols="6"
                    >
                      <v-text-field
                        v-model="form.Cnpj"
                        v-mask="maskCpf"
                        label="CNPJ *"
                        :rules="requiredRules"
                        return-masked-value
                      />
                    </v-col>
                    <v-col
                      cols="6"
                    >
                      <v-autocomplete
                        v-model="form.estado"
                        label="Estado"
                        name="estado_agroindustria"
                        :items="estado"
                        item-text="nome"
                        item-value="id"
                        @change="changeCidade"
                      />
                    </v-col>
                    <v-col
                      cols="6"
                    >
                      <v-autocomplete
                        v-model="form.cidade"
                        label="Cidade"
                        :items="cidade"
                        item-text="nome"
                        item-value="id"
                        :disabled="disableCidade"
                      />
                    </v-col>
                    <v-col
                      cols="4"
                    >
                      <v-text-field
                        v-model="form.Logradouro"
                        label="Logradouro"
                      />
                    </v-col>
                    <v-col
                      cols="2"
                    >
                      <v-text-field
                        v-model="form.Numero"
                        label="Numero"
                      />
                    </v-col>
                    <v-col
                      cols="6"
                    >
                      <v-text-field
                        v-model="form.Bairro"
                        label="Bairro *"
                        :rules="requiredRules"
                      />
                    </v-col>
                    <v-col
                      cols="6"
                    >
                      <v-text-field
                        v-model="form.Complemento"
                        label="Complemento"
                      />
                    </v-col>
                    <v-col
                      cols="3"
                    >
                      <v-text-field
                        v-model="form.Cep"
                        v-mask="maskCep"
                        :rules="requiredRules"
                        label="CEP *"
                      />
                    </v-col>
                    <v-col
                      cols="3"
                    >
                      <v-text-field
                        v-model="form.TelRes"
                        v-mask="maskTelRes"
                        label="Telefone"
                        type="tel"
                        return-masked-value
                      />
                    </v-col>
                    <v-col
                      cols="6"
                    >
                      <v-text-field
                        v-model="form.email"
                        :rules="emailRules"
                        label="E-mail"
                        type="email"
                        return-masked-value
                      />
                    </v-col>
                  </v-row>
                </v-list-item-content>
              </v-card>
              <!-- <v-card>
                <v-list-item-content>
                  <v-card-title
                    class="headline mx-auto"
                  >
                    Dados Técnicos
                  </v-card-title>
                  <v-row
                    v-if="!loading"
                    class="pa-3"
                  >
                    <v-col
                      cols="6"
                    >
                      <v-text-field
                        v-model="form.captacao"
                        label="Captação"
                      />
                    </v-col>
                    <v-col
                      cols="6"
                    >
                      <v-text-field
                        v-model="form.fornecedores"
                        label="Fornecedores"
                      />
                    </v-col>
                  </v-row>
                </v-list-item-content>
              </v-card> -->
              <v-btn
                type="submit"
                :disabled="salvando"
                :loading="salvando"
                :color="!$route.params.codAgroindustria ? 'success' : 'warning'"
                form="form"
              >
                {{ btnNome }}
              </v-btn>

              <router-link
                :disabled="salvando"
                to="listar-agroindustrias"
              >
                <v-btn
                  :disabled="salvando"
                  color="error"
                  class="ml-3"
                >
                  Cancelar
                </v-btn>
              </router-link>
            </v-form>
          </div>
        </v-card>
      </template>
    </div>
  </v-card>
</template>
0 Answers
Related