简体   繁体   中英

Submit PUT form in vuetify and laravel

im tryng to submit a form with a Laravel API in Vuejs. But i have this issue when i need to edit the user data.

Im using this vform method because i want to upload a avatar picture and in this github accound this guys add this function with npm. ( https://github.com/cretueusebiu/vform/blob/master/example/upload.html ).

The problem i have is in the edit part, when i add a new user the function works. But in edit its says

TypeError: this.form_edit.submit is not a function

Here is my code in the edit view.

If anyone dont understand, sorry english is not my first lenguage, so if you want to ask anything, please do it.

<template>
  <v-dialog v-model="dialog" width="90rem" scrollable persistent>
      <v-card outlined class="m-auto center">
        <v-card-title  class="headline grey lighten-2" primary-title>
        {{ $t('edita_usuario') }}
                  <v-spacer></v-spacer>
             <v-card-actions >
                <v-btn color="error"  @click="closeModal">{{ $t('cancel') }}</v-btn>
                <v-btn color="primary"  @click="update">  {{ $t('update') }}</v-btn>
              </v-card-actions>
      </v-card-title>

        <v-divider class="mx-4" /><br>

        <v-card-text>
          <form @submit.prevent="update" enctype="multipart/form-data">


            <!--autocomplete="off" -->

             <Success :message="$t('usuario_editado')" v-if="successMessage"/>

             <Error :message="errorMessage" v-if="errorAlert"/>

             <v-spacer></v-spacer>

              <v-row no-gutters>
                  <v-col cols="11"></v-col>
                <v-col cols="3">

                <Card title="" :img="profilePicture" width="300" height="300" />

                <v-col cols="10">
                <v-file-input :label="$t('foto_perfil')" clearable filled prepend-icon="mdi-camera" ref="linkfoto" name="linkfoto" v-on:change="ImageChange"></v-file-input>
                </v-col>
                </v-col>

                <v-col cols="9">
                   <v-row>
                      <v-col cols="5">
                        <v-text-field v-model="form_edit.nombres" :label="$t('name')" name="nombres" />
                      </v-col>

                      <!-- Apellido -->
                      <v-col cols="5">
                        <v-text-field v-model="form_edit.apellidos" :label="$t('last_name')" name="apellidos"/>
                      </v-col>
                   </v-row>

                    <v-row>
                      <v-col cols="10">
                        <v-text-field v-model="form_edit.email" :label="$t('email')" name="email"/>
                      </v-col>
                    </v-row>



                    <v-row>
                      <v-col cols="5">
                         <v-select

         <v-spacer></v-spacer><br>

        <label class="title">Datos de usuario</label>

        <v-row class="justify-center">
             <v-col cols="2"></v-col>
             <v-col cols="4">
              <v-text-field v-model="form_edit.alias" :label="$t('usuario')"  name="alias" autocomplete="new-user"/>
             </v-col>

             <v-col cols="4">
              <v-text-field v-model="form_edit.password" :label="$t('password')" :append-icon="show ? 'mdi-eye' : 'mdi-eye-off'" :type="show ? 'text' : 'password'" name="password" @click:append="show = !show" disabled autocomplete="newpassword" />
             </v-col>
          </v-row>

                 <!-- Perfil -->
             <v-row class="justify-center">
              <v-col cols="2"></v-col>
                <v-col cols="4">
                 <v-select :items="perfiles" item-text="nombreperfil" item-value="idperfil" :label="$t('tipo_usuario')" v-model="form_edit.idperfil" name="idperfil" required />
              </v-col>

              <v-col cols="4">
                <v-textarea name="input-7-1"
                  filled :label="$t('email_firma')" auto-grow v-model="form_edit.saludo"></v-textarea>
             </v-col>

          </v-row>
             <v-divider/><br>



          </form>
        </v-card-text>
      </v-card>
  </v-dialog>
</template>
<script>

import { mapGetters } from 'vuex'
import Form from 'vform'
import objectToFormData from 'object-to-formdata'
import axios from 'axios'

export default {
  middleware: 'admin',
  name: 'FormEditUser',

  props:['dialog','id'],


  data: () => ({
     form_edit: new Form({
      alias: '',
      password: '',
      nombres:'',
      apellidos:'',
      email:'',
      idperfil:'',
      saludo:'',
      linkfoto:'',
    }),

    profilePicture:'',
    paises:[],
    perfiles:[],

    show: false,
    successMessage : false,
    errorAlert : false,
    errorMessage:'',

  }),

  metaInfo () {
    return { title: 'SIIGDE - ' + this.$t('admin') }
  },


mounted: function(){
    this.loadUsuario();
    this.getPerfiles();
  },


methods: {

 update:function() {

  this.form_edit.submit('put', '/api/usuarios'+this.id, {
        transformRequest: [function (data, headers) { // Transforma el vform a formdata para la imagen. Si no anda tirar npm install
          return objectToFormData(data)
        }],
      })

  //axios.put('/api/usuarios/'+this.id, this.form_edit)
      .then(response => {
        this.successMessage = true;
        this.errorAlert = false;
      })
      .catch(error =>{
        this.errorMessage = error.response.data.errors
        this.successMessage = false;
        this.errorAlert = true
;      })
    },

     getPerfiles : function(){
      axios.get('/api/perfiles/0')
      .then(function(response){
        this.perfiles = response.data;
      }.bind(this));  
    },

  // metodos de la imagen para que cargue o se borre
    ImageChange(e) {
      this.UploadImage(e)
    },

    UploadImage(file){
      let reader = new FileReader();

      reader.onload = (e) =>{
        this.profilePicture = e.target.result; //Asigno al input para que muestre la imagen antes del submit
        this.form_edit.linkfoto = file;
      }
      if(file){
      reader.readAsDataURL(file);
      }else{
        this.profilePicture = 'https://www.gravatar.com/avatar/8ab904bf2bea2e8f3c7d76f04df2087c.jpg?s=200&d=mm'
      }
    },

    closeModal: function(){
      let close = false;
      this.errorAlert = false;
      this.successMessage = false;
      this.$emit('closeDialog',close);
    },

    loadUsuario(){
        axios.get('/api/usuarios/'+this.id+'/edit') // Aca traigo los datos del usuario por id que mando en la url
      .then((response) => {
        this.form_edit = response.data;
        if(!this.form_edit.linkfoto){
          this.profilePicture = 'https://www.gravatar.com/avatar/8ab904bf2bea2e8f3c7d76f04df2087c.jpg?s=200&d=mm';
        }else{
          this.profilePicture = this.form_edit.linkfoto;
        }

      });
    },
  }, // Cierra el methods
}

</script>

You are already saying to run the update function if the use submits your form. In your update you do not need to submit the form since the event already exists.

Further I am not sure what this line is doing there:

<form @submit.prevent="update" enctype="multipart/form-data">

Why are you trying to achieve with ...prevent="update"

I would simply post your form using an xhr request, you could use axios for instance like this:

  data() {
    return {
      fields: {},
      errors: {},
    }
  },
  methods: {
    submit() {
      this.errors = {};
      axios.post('/api/usuarios'+this.id, this.fields).then(response => {
        alert('Message sent!');
        // your logic ...
      }).catch(error => {
        if (error.response.status === 422) {
          this.errors = error.response.data.errors || {};
        }
      });
    },

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM