Advertisement
Guest User

Untitled

a guest
Jun 17th, 2019
141
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 9.23 KB | None | 0 0
  1. <template>
  2. <div class="tab-pane" id="settings">
  3. <form @submit.prevent="updateReg()" class="form-horizontal" novalidate>
  4. <!-- ... -->
  5. <div class="form-row">
  6. <div class="col-md-4 mb-1">
  7. <div class="form-group mb-0">
  8. <div class="row">
  9. <div class="col-8 mx-auto text-center">
  10. <img class="input-img-avatar" :src="avatar" alt="Imagen de usuario seleccionada">
  11. </div>
  12. </div>
  13. <div class="row mt-0">
  14. <div class="col-8 mx-auto text-center">
  15. <label class="btn-bs-file btn btn-primary">
  16. Cargar nuevo avatar
  17. <input type="file" name="avatar" @change="getNewAvatar" accept="image/*" ref="inputFileAvatar" />
  18. </label>
  19. <span v-if="errors.has('avatar')" class="block text-sm text-danger mt-2">{{ errors.get('avatar') }}</span>
  20. </div>
  21. </div>
  22. </div>
  23. </div>
  24. </div>
  25.  
  26. <div class="form-row">
  27. <div class="col-md-12 col-sm-offset-2 col-sm-10 text-right">
  28. <button type="submit" class="btn btn-success" title="Actualizar registro">Actualizar</button>
  29. </div>
  30. </div>
  31. </form>
  32.  
  33. .btn-bs-file{
  34. position:relative;
  35. font-weight: normal !important;
  36. }
  37. .btn-bs-file input[type="file"]{
  38. position: absolute;
  39. top: -9999999;
  40. filter: alpha(opacity=0);
  41. opacity: 0;
  42. width:0;
  43. height:0;
  44. outline: none;
  45. cursor: inherit;
  46. }
  47.  
  48. <script>
  49.  
  50. //librería para tratar los errores capturados en el servidor
  51. import { Errors } from '../../libs/errors';
  52. export default {
  53. mounted() {
  54. console.log('Component mounted.');
  55.  
  56. //Recibiendo evento(s) si emitido(s) (en este caso, desde su componente Padre)
  57. BusEvent.$on('fillProfEditFormEvent', (regID) => {
  58. this.fillEditFormReg(regID);
  59. });
  60. },
  61.  
  62. //datos devueltos por el componente:
  63. data() {
  64. return {
  65. urlBase: '/api/admin/users',
  66. //variable que guarda el archivo seleccionado
  67. //indicando nombre del archivo precedido de la ruta completa
  68. //hacia el archivo guardado en el servidor
  69. avatar: null,
  70. avatar_max_size: null,
  71. //variable para almacenar los datos del registro a almacenar
  72. //objReg: {},
  73. objReg: {
  74. 'name': '',
  75. 'lastname': '',
  76. 'phone_int': '',
  77. //y más datos que no pongo para que no sea más largo
  78. 'avatar': '',
  79. //para la edición
  80. 'id': '',
  81. },
  82. //posibles errores
  83. errors: new Errors(),
  84. }
  85. },
  86.  
  87. methods: {
  88.  
  89. /**
  90. * Mostrando datos cargados del registro para editar
  91. */
  92. fillEditFormReg(regID) {
  93. console.log('Cargando datos del registro correspondiente [' + regID + ']');
  94. let url = this.urlBase + '/' + regID;
  95. axios.get(url)
  96. .then(response => { //SI TODO OK
  97. console.log(response.data)
  98. //this.objReg = response.data
  99. //this.objReg = response.data.user
  100. this.objModelDependenciesLists = response.data.dependenciesLists
  101.  
  102. this.objReg = {
  103. 'name': response.data.user.name,
  104. 'lastname': response.data.user.lastname,
  105. 'phone_int': response.data.user.phone_int,
  106. //...
  107. 'avatar': response.data.user.avatar,
  108. //...
  109. //para la edición
  110. 'id': response.data.user.id,
  111. };
  112. this.avatar_max_size = response.data.user_icon_max_size
  113. this.avatar = `/storage/images/profile/${this.objReg.avatar}`
  114. //carga inicial de la imagen precedida de su ruta
  115.  
  116. })
  117. .catch(error => { //SI HAY ALGÚN ERROR
  118. console.log(error.response.data.errors);
  119. });
  120. },
  121.  
  122. /**
  123. * Lanzado al cambiar el valor del input de archivo del formulario
  124. */
  125. getNewAvatar(e) {
  126. let file = e.target.files[0];
  127. //Sacando características referidas al archivo cargado
  128. //en el input de archivo dentro de un array JSON
  129. console.log(file);
  130.  
  131. if(file['size'] <= this.avatar_max_size) {
  132. //Leyendo el archivo cargado
  133. this.readFile(file);
  134. } else {
  135. //Reseteando valor...
  136. this.cancelFileAction();
  137. alert('El archivo cargado tiene un tamaño en disco más grande de lo permitido.');
  138. }
  139. },
  140.  
  141. readFile(file) {
  142. let reader = new FileReader();
  143. reader.readAsDataURL(file);
  144. reader.onload = e => {
  145. //Pasando la imagen seleccionada en Base64 a la variable
  146. //que se caraga en la etiqueta IMG
  147. this.avatar = e.target.result;
  148. console.log('Esto es ahora AVATAR: ' + this.avatar)
  149. //Asignando la imagen seleccionada en Base64 a
  150. //la propiedad 'avatar' del objeto objReg
  151. this.$set(this.objReg, 'avatar', e.target.result)
  152. }
  153. },
  154.  
  155. cancelFileAction() {
  156. //Reseteando imagen y volviendo a valor anterior...
  157. this.avatar = `/storage/images/profile/${this.objReg.avatar}`;
  158. //Limpiando elementos...
  159. this.clearFileAction();
  160. },
  161.  
  162. clearFileAction() {
  163. //Reseteando imagen y volviendo a valor anterior...
  164. //Reseteando contenido del INPUT File
  165. const input = this.$refs.inputFileAvatar;
  166. input.type = 'text';
  167. input.type = 'file';
  168. },
  169.  
  170. /**
  171. * Actualizando registro
  172. */
  173. updateReg() {
  174. console.log('Actualizando registro... [' + this.objReg.id + ']');
  175. let url = this.urlBase + '/' + this.objReg.id;
  176. axios.put(url, this.objReg)
  177. .then((response) => { //SI TODO OK
  178.  
  179. //vaciando los posibles errores que se produjeron
  180. this.errors.clear();
  181.  
  182. //Emitiendo evento global para recargar
  183. //en el panel izquierdo de datos resumen
  184. // >> con el ID pasado
  185. BusEvent.$emit('fillProfDataResumEvent', this.objReg.id);
  186.  
  187. //Lanzando notificación satisfactoria
  188. toast({
  189. type: 'success',
  190. title: 'Registro actualizado'
  191. });
  192. })
  193. .catch(error => { //SI HAY ALGÚN ERROR
  194. //registrando los errores recibidos
  195. this.errors.record(error.response.data.errors);
  196. });/**/
  197. },
  198.  
  199. },
  200. }
  201.  
  202. </script>
  203.  
  204. public function update(UserUpdateRequest $request, $id)
  205. {
  206. $user = User::withTrashed()->findOrFail($id);
  207. $user->name = $request->name;
  208. $user->lastname = $request->lastname;
  209. //...
  210.  
  211. //USERNAME
  212. $user->username = Str::slug($request->name . ' ' . $request->lastname);
  213.  
  214. //AVATAR
  215. //Si existe un valor para este INPUT...
  216. $hay_foto = '';
  217. $name_file = '';
  218. $user_username = '';
  219. //return $request->all();
  220. if($request->has('avatar')) {
  221. //if($request->hasFile('avatar')) {
  222. //if($request->avatar) {
  223. $hay_foto = 'SI hay';
  224. $user_username = $user->username;
  225. $extension_file = explode(';', explode('/', $request->avatar)[1] )[0];
  226. $name_file = $user->username . '.' . $extension_file;
  227. //Guardando archivo en STORAGE
  228. $request->avatar->storeAs('public' . '/images/profile', $name_file);
  229. //$request->file('avatar')->storeAs('public' . '/images/profile', $name_file);
  230. $user->avatar = $name_file;
  231. } else {
  232. $hay_foto = 'NO hay';
  233. }
  234.  
  235. //Si no es NULO
  236. if( !is_null($request->password) ) {
  237. $user->password = Hash::make($request->password);
  238. }
  239. $user->profile_id = $request->profile_id;
  240. $user->save();
  241.  
  242. return [
  243. 'message' => 'Actualizando el registro con ID => [' . $id . ']',
  244. 'avatar' => $request->avatar,
  245. 'name_file' => $name_file,
  246. 'user_username' => $user_username,
  247. 'hay_foto' => $hay_foto,
  248. ];
  249. }
  250.  
  251. $request->avatar->storeAs('public' . '/images/profile', $name_file);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement