SliderInput.php 2.12 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
<?php
/**
 * @link http://www.yiiframework.com/
 * @copyright Copyright (c) 2008 Yii Software LLC
 * @license http://www.yiiframework.com/license/
 */

namespace yii\jui;

use yii\helpers\Html;

/**
 * SliderInput renders a slider jQuery UI widget that writes its value into hidden input.
 *
 * For example,
 *
 * ```
18
 * echo SliderInput::widget([
19
 *     'model' => $model,
Alexander Makarov committed
20
 *     'attribute' => 'amount',
21 22 23 24 25 26 27 28 29 30
 *     'clientOptions' => [
 *         'min' => 1,
 *         'max' => 10,
 *     ],
 * ]);
 * ```
 *
 * The following example will use the name property instead:
 *
 * ```
31
 * echo SliderInput::widget([
32 33 34 35 36 37 38 39 40 41 42 43 44 45
 *     'name' => 'amount',
 *     'clientOptions' => [
 *         'min' => 1,
 *         'max' => 10,
 *     ],
 * ]);
 * ```
 *
 * @see http://api.jqueryui.com/slider/
 * @author Alexander Makarov <sam@rmcreative.ru>
 * @since 2.0
 */
class SliderInput extends InputWidget
{
46 47 48
	/**
	 * @inheritDoc
	 */
49
	protected $clientEventMap = [
50 51 52 53 54 55
		'change' => 'slidechange',
		'create' => 'slidecreate',
		'slide' => 'slide',
		'start' => 'slidestart',
		'stop' => 'slidestop',
	];
56 57
	/**
	 * @var array the HTML attributes for the container tag.
58
	 * @see \yii\helpers\Html::renderTagAttributes() for details on how attributes are being rendered.
59 60 61 62 63 64 65 66 67 68 69 70 71
	 */
	public $containerOptions = [];

	/**
	 * @inheritdoc
	 */
	public function init()
	{
		parent::init();
		if (!isset($this->containerOptions['id'])) {
			$this->containerOptions['id'] = $this->options['id'] . '-container';
		}
	}
72 73 74 75 76 77

	/**
	 * Executes the widget.
	 */
	public function run()
	{
78
		echo Html::tag('div', '', $this->containerOptions);
79 80

		if ($this->hasModel()) {
81
			echo Html::activeHiddenInput($this->model, $this->attribute, $this->options);
82
			$this->clientOptions['value'] = $this->model{$this->attribute};
83
		} else {
84
			echo Html::hiddenInput($this->name, $this->value, $this->options);
85
			$this->clientOptions['value'] = $this->value;
86 87 88 89
		}

		if (!isset($this->clientEvents['slide'])) {
			$this->clientEvents['slide'] = 'function(event, ui) {
90
				$("#' . $this->options['id'] . '").val(ui.value);
91 92 93
			}';
		}

94
		$this->registerWidget('slider', SliderAsset::className(), $this->containerOptions['id']);
95
	}
96
}