Skip to content

Instantly share code, notes, and snippets.

@mikbox74
Created June 2, 2018 11:20
Show Gist options
  • Save mikbox74/9bf813c3b5b5550205daa7a080eec6cd to your computer and use it in GitHub Desktop.
Save mikbox74/9bf813c3b5b5550205daa7a080eec6cd to your computer and use it in GitHub Desktop.
2amigos/yii2-selectize-widget: how to set up default value when options are customized
<?php
namespace common\modules\appearance\widgets\backend;
use yii\web\JsExpression;
/**
* Selectize customization
*
* @author Michail Urakov
*/
class Selectize extends \dosamigos\selectize\SelectizeDropDownList
{
/**
* @var array Items array (value => description pairs)
*/
public $items = [];
/**
* {@inheritdoc}
*/
public function init()
{
$items = [];
$items[] = ['name' => '', 'description' => 'NOT_SELECTED'];
foreach ($this->items as $name => $description) {
$items[] = compact('name', 'description');
}
$this->clientOptions = [
'valueField' => 'name',
'labelField' => 'description',
'searchField' => ['name', 'description'],
'persist' => false,
'create' => false,
'options' => $items,
'maxItems' => 1,
'allowEmptyOption' => true,
'items' => [$this->model->{$this->attribute}], //IT'S VERY IMPORTANT to set up this otpion if you expect default value will be empty
'render' => [
'option' => new JsExpression('function(item, escape) {'
. 'return "<div><div><b class=\\"text-turquoise\\">"'
. ' + item.description + '
. '"<\\/b><\\/div>'
. '<div class=\\"text-concrete\\">"'
. ' + (item.name !=="" ? item.name: "-") + '
. '"<\\/div><\\/div>";'
. '}'),
'item' => new JsExpression('function(item, escape) {'
. 'return "<div class=\\"item\\" data-value=\\""'
. ' + item.name +'
. '"\\" data-desc=\\""'
. ' + item.description +'
. '"\\">" + item.description + "<\\/div>";'
. '}'),
],
];
parent::init();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment