CJuiSliderInput 專為表單設計,直接綁定模型屬性,支援驗證規則、AJAX 提交與隱藏欄位同步。
<?php $form=$this->beginWidget('CActiveForm', array('id'=>'slider-form')); ?>
<?php echo $form->errorSummary($model); ?>
<?php $this->widget('zii.widgets.jui.CJuiSliderInput', array(
'model' => $model,
'attribute' => 'size', // 對應模型屬性
'name' => 'my_slider',
'value' => 50,
'event' => 'change', // 觸發模型更新的事件
'options' => array(
'min' => 0,
'max' => 100,
'slide' => 'js:function(event,ui){ $("#amount").text(ui.value); }',
),
'htmlOptions' => array('style' => 'width:200px; float:left;'),
)); ?>
<center id="amount" style="margin-left:215px;">50</center>
<br><br>
<div class="row submit">
<?php echo CHtml::submitButton('送出'); ?>
</div>
<?php $this->endWidget(); ?>
class DataModel extends CFormModel {
public $size;
public function rules() {
return array(
array('size', 'numerical', 'integerOnly' => true, 'min' => 0, 'max' => 100),
array('size', 'safe'), // 大量賦值允許
);
}
public function attributeLabels() {
return array('size' => '尺寸百分比');
}
}
public function actionIndex() {
$model = new DataModel();
$model->size = 50; // 預設值
if (isset($_POST['DataModel'])) {
$model->attributes = $_POST['DataModel'];
if ($model->validate()) {
$this->render('result', array('model' => $model));
return;
}
}
$this->render('index', array('model' => $model));
}
<h2>提交結果</h2>
<p>尺寸: <?php echo $model->size; ?>%</p>
| 特性 | CJuiSlider | CJuiSliderInput |
|---|---|---|
| 表單整合 | 需手動同步 hidden input | 自動綁定模型屬性 |
| 驗證支援 | 無 | 支援 CModel 驗證規則 |
| 適用場景 | UI 控制、即時預覽 | 表單輸入、設定儲存 |
| 事件觸發更新 | 需自行實作 | event 選項指定 |
<?php foreach (array('brightness', 'contrast', 'saturation') as $attr): ?>
<div class="slider-row">
<label><?php echo $model->getAttributeLabel($attr); ?></label>
<?php $this->widget('zii.widgets.jui.CJuiSliderInput', array(
'model' => $model,
'attribute' => $attr,
'options' => array('min' => -100, 'max' => 100, 'value' => 0),
)); ?>
<span class="value-display">0</span>
</div>
<?php endforeach; ?>
event: 'change' 只在滑動結束更新模型,'slide' 會頻繁觸發驗證影響效能attribute 值CActiveForm 的 enableAjaxValidation 可即時驗證