2016-07-15 83 views
1

控制器@更新如何在使用AJAX數據和laravel的同時設置Select2的選定值?

//Update 
    $course = Course::findOrFail($id); 
    $course->name = Input::get('name'); 
    $course->code = Input::get('code'); 
    $course->credits = Input::get('credits'); 
    $course->description = Input::get('description'); 

    $course->tags()->sync(Input::get('tags')); // Use of sync method 

    //return [$course]; 
    $course->save(); 
    //Redirect 
    Session::flash('message', 'Successfully edited the course : '.$course->name); 
    return $this->show($course->code); 

HTML

<pre> 
<div class="form-group"> 
    {{Form::label('tags', 'Tag')}} 
    {{Form::select('tags[]',[],null,array('multiple'=>'multiple','name'=>'tags[]','id'=>'tag_list','class'=>'form-control'))}} 
    </div> 
</pre> 

選擇二腳本

function tagResultTemplater(tag) { 
    return tag.name + " : " + tag.type; 
    } 

    function tagSelectionTemplater(tag) { 
    return tag.id + " "+tag.name + " : " + tag.type; 
    } 
    $("#tag_list").select2({ 
    ajax: { 
     url: "{!! route('tags.json') !!}", 
     dataType: 'json', 
     delay: 250, 
     tags: true, 
     data: function (params) { 
     return { 
      q: params.term, // search term 
     }; 
     }, 
     processResults: function (data) { 
     return { 
      results: data 
     }; 
     }, 
     cache: true 
    }, 
    minimumInputLength: 1, 
    placeholder: function(){ 
     $(this).data('placeholder'); 
    }, 
    templateResult: tagResultTemplater, 
    templateSelection: tagSelectionTemplater 

    }); 

我工作的課程管理系統作爲畢業項目,在短有一個馬至於許多課程和標籤之間的關係,我想用Select2包中的同步方法來以方便的方式附加和解除課程中的標籤,但我無法找到一種方法來設置Select2的選定值,同時使用ajax數據。如果任何人都可以提供一個關於如何做到這一點的簡單指南指南,那將是非常感謝:D。

回答

0

在類似情況下,我必須避免使用表單生成

<select name="tags" id="tag_list" class="form-control" multiple> 
    @foreach ($course->tags as $tag) 
     <option value="{{ $tag->id }}" selected>{{ $tag->name }}</option> 
    @endforeach 
</select> 
+0

的問題是,當你使用AJAX的數據與選擇二是刪除所有書面方案,並與來自JSON響應重新寫他們ajax請求 –

+0

我也想使用這種方法,但現在的問題是,templateResult 和 templateSelection返回undefined:undefined 您對如何編寫選項標籤以便Select2可以提取所需數據有什麼想法嗎? –

+0

我之前沒有使用過自定義模板。但根據select2文檔,它應該是相同的。使用預先選擇的選項檢查[鏈接](https://select2.github.io/examples.html#data-ajax)ajax示例,不要忘記檢查模板的源代碼。我也會盡量在稍後測試它 – Gostwow

相關問題