Christophvh
Christophvh

Reputation: 13244

Add dynamic Colorblock in select2 multi-select - Laravel 5.2

I store Hex colorcodes in my database . What i like to achieve is this (Or something similar): enter image description here enter image description here

It should work when selecting the values and when the values are selected.

In a normal multiselect i can do something like this:

<div class="col-sm-10">
<select id="colors" name="colors[]" multiple class="form-control">
  @foreach($colors as $key => $color)
    <option value="{{$key}}" style="background-color:{{$color->code}}"></option>
  @endforeach
 </select>
</div>

But when using the Select2 - plugin, the styles get overwritten. I also tried to add a span or div inside the select-option like so:

<option value="{{$key}}"><span style="background-color:{{$color->code}}"></span>{{$color->code}}</option>

But this also gets overwritten.

I found this example in the documentation, but i am not really sure how to adapt it to use with laravel

function formatState (state) {
  if (!state.id) { return state.text; }
  var $state = $(
    '<span><img src="vendor/images/flags/' + state.element.value.toLowerCase() + '.png" class="img-flag" /> ' + state.text + '</span>'
  );
  return $state;
};

$(".js-example-templating").select2({
  templateResult: formatState
});

Select 2 Version : 4.0.2

Upvotes: 0

Views: 1828

Answers (1)

Tim Van Dijck
Tim Van Dijck

Reputation: 552

This shouldn't be a problem. It's just a matter of using the right classes to style your dropdown and using the template functions like you said.

Here's a quick demo of how you can do it:

<select>
  <option>#232342</option>
  <option>#ffd800</option>
  <option>#ff1200</option>
</select>

<script type="text/javascript">
$(document).ready(function() {
  function formatColor (state) {
    if (!state.id) { return state.text; }
    var $state = $(
      '<span style="background-color: ' + state.text + '" class="color-label"></span><span>Color ' + state.text + '</span>'
    );
    return $state;
  };


  $('select').select2({
    width: "300px",
    templateResult: formatColor,
    templateSelection: formatColor
  });  
});
</script>

https://plnkr.co/edit/Btjj5IrE9C4G7UO0mdRY?p=preview

In the example I used a static select but you can populate the select with Laravel just like you did in your code sample.

Upvotes: 1

Related Questions