mercredi 6 novembre 2019

How to get value of Selected items of Select2 when submitted?

What options I should set to get the value of the options when I submit the form?

I am using Select2. I have given the code I have to setup the select2, controller that returns the data, the html code that renders the element.

Html Code to add the select2 element:

<div class="form-group row"><label class="col-lg-2 col-form-label">Keyword</label>
  <div class="col-lg-10">
      <select class="form-control w-50" name="keywords[]"     id="keyword" multiple="multiple">
     </select>
   <span class="form-text m-b-none">One or multiple keywords</span>
 </div>
</div>

Datasource is an Ajax call:

$(document).ready(function() {
    $('#keyword').select2({
        tags: true,
        tokenSeparators: [',', ' '],

   placeholder: 'Select keyword',
    ajax: {
      url: 'https://rankypro.dev/app/json/keywords',
      dataType: 'json',
      delay: 250,
      processResults: function (data) {
        return {
          results:  $.map(data, function (item) {
                return {
                    text: item.name,
                    id: item.id
                }
            })
        };
      },
      cache: true
    }
  });

Controller:

public function getKeywords(Request $request){

    $search = $request->search;

    if($search == ''){
        $keywords = Term::orderby('name','asc')
                    ->select('id','name')
                    ->where('taxonomy','keyword')
                    ->limit(5)
                    ->get();
     }else{
        $keywords = Term::orderby('name','asc')->select('id','name')
                        ->where('taxonomy','keyword')
                        ->where('name', 'like', '%' .$search . '%')
                        ->limit(5)
                        ->get();
     }

   $results = array();
        foreach($keywords as $keyword){
            $results[] = array(
                "id"=>$keyword->id,
                "text"=>$keyword->name
            );
        }
   echo json_encode($results);
   exit();
}

I am testing with:

public function store(Request $request)
{

    dd($request->keywords);
}

I get the following:

array:2 [
     0 => "Tools"
     1 => "SEO"
  ]

I actually need ids of the keywords. Would you please give some hints how can I get that.



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire