X-editable 사용방법

Admin 2020.04.27 12:32 조회 수 : 11

aJax를 이용하여 DB 컬럼 값을 저장하는 방법이다.

일반적으로 HTML Form 양식을 통해서 DB에 값을 저장한다.

간단히 몇개의 자료를 저장하기 위해 HTML Form을 만들어서 처리하는 것이 번거로울때가 많다.

그럴때 X-editable 을 사용하면 편리하다.

 

<link rel="stylesheet" type="text/css" href="{{asset('css/bootstrap-editable.css')}}">
<div class="row">
  <div class="col">
    <div class="form-group">
      <div class="controls">
        <label>Name</label>
        <p><a href="#" class="bt-text" data-clear="true" data-type="text" data-placement="right" data-title="User Name" data-url="{{ route('user.edit' ) }}" data-pk="{{ Auth()->user()->id }}" data-name="name" data-validation-required-message="This name field is required">{{ Auth()->user()->name }}</a></p>
      </div>
    </div>
  </div>
  <div class="col">
    <div class="form-group">
      <div class="controls">
        <label>Gender</label>
        <p><a href="#" class="bt-select" data-clear="true" data-type="select" data-placement="right" data-title="Gender" data-url="{{ route('user.edit' ) }}" data-pk="{{ Auth()->user()->id }}" data-name="gender" data-validation-required-message="This Gender field is required">Gender</a></p>
      </div>
    </div>
  </div>
</div>
<script type="text/javascript" src="{{asset('js/scripts/editable/bootstrap-editable.js')}}"></script>
<script type="text/javascript" src="{{asset('js/scripts/editable/moment.js')}}"></script>
<script type="text/javascript">
jQuery(document).ready(function($) {
  var csToken = $('meta[name="csrf-token"]').attr('content');
  $.fn.editable.defaults.mode = 'inline';
  $.fn.editable.defaults.ajaxOptions = {type: "PUT"};
  $.ajaxSetup({
    headers: { 'X-CSRF-TOKEN': csToken }
  });
  $('.bt-text').editable({
    type: 'text',
    validate: function(value){
      if($.trim(value) === '') { return 'This '+$(this).data('title')+' field is required'; }
    },
    success: function(response, newValue) {
      //console.log(response);
    }
  });

  $('.bt-select').editable({
    prepend: "Gender",
    value: '',
    source: [
      {value: 1, text: 'Male'},
      {value: 2, text: 'Female'}
    ],
    display: function(value, sourceData) {
      var colors = {"": "gray", 1: "green", 2: "blue"},
      elem = $.grep(sourceData, function(o){return o.value == value;});
      if(elem.length) {
        $(this).text(elem[0].text).css("color", colors[value]);
      } else {
        $(this).empty();
      }
    }
  });

  $('.bt-address').editable({
    type: 'address',
    mode: 'inline',
    url: '{{ route("user.update") }}',
    value: {
      city: "{{ $user->city }}",
      state: "{{ $user->state }}",
      address: "{{ $user->address }}",
      zip: "{{ $user->zip }}"
    },
    validate: function(value){

    },
    success: function(response, newValue) {
      toastr.info(response.msg, 'Success', { "hideDuration": 500, "timeOut": 3000 });
    }
  });

});
</script>