我想在yii中创建一个可搜索的下拉列表,它从数据库中获取数据,就像在此链接demo中一样,并将其存储在数据库中。我知道如何制作一个下拉列表,但我的任务是创建一个可搜索的下拉列表,就像我开始输入时,下拉列表打开并显示数据库中的数据。 我在(包)视图中,其中(package-item)是想要可搜索下拉的字段。
<?php
/* @var $this PackageController */
/* @var $model Package */
/* @var $form BSActiveForm */
?>
<?php $form=$this->beginWidget('bootstrap.widgets.BsActiveForm', array(
'id'=>'package-form',
// Please note: When you enable ajax validation, make sure the corresponding
// controller action is handling ajax validation correctly.
// There is a call to performAjaxValidation() commented in generated controller code.
// See class documentation of CActiveForm for details on this.
'enableAjaxValidation'=>false,
)); ?>
<p class="help-block">Fields with <span class="required">*</span> are required.</p>
<?php echo $form->errorSummary($model); ?>
<?php echo $form->textFieldControlGroup($model,'package_name',array('maxlength'=>45)); ?>
<?php echo $form->textFieldControlGroup($model,'package_item',array('maxlength'=>45)); ?>
<?php echo $form->textFieldControlGroup($model,'package_detail',array('maxlength'=>45)); ?>
<?php echo BsHtml::submitButton('Submit', array('color' => BsHtml::BUTTON_COLOR_PRIMARY)); ?>
<?php $this->endWidget(); ?>
答案 0 :(得分:0)
autocomplete
,那么这可能有所帮助:在您看来:
<?php
echo "<div class='auto-search'>";
$this->widget('zii.widgets.jui.CJuiAutoComplete', array(
'id'=>'package_item',
'name'=>'package_item',
'source'=>$this->createUrl('site/suggestItem'),
'htmlOptions'=>array(
'class'=>'package_item',
'placeholder'=>"Search package.."
),
));
echo "</div>";
?>
在您的控制器中(在这种情况下为siteController
)创建一个新操作:
<?php
public function actionsuggestItem()
{
$request = trim($_GET['term']);
$data = array();
if($request != ''){
//your query to database to get package items.
$packageModel = Package::model()->findAll("packagename=$request");
foreach($packageModel as $get){
$data[] = $get->packagename;
}
echo json_encode($data);
}
Yii::app()->end();
}
?>
dropdown
和 autocomplete
然后您可以使用此Select2 Extension
在您看来:
<?php $this->widget('ext.select2.ESelect2',array(
'model'=>$model,
'attribute'=>'package_item',
'data'=>$model->searchItem(),
); ?>
在你的模特中:
<?php
public function searchItem() {
$data = array();
$packageModel = Package::model()->findAll();
foreach($packageModel as $get){
$data[] = $get->packagename;
}
return $data;
Yii::app()->end();
}
?>
请注意,这些只是示例,请根据您的需要进行修改。
答案 1 :(得分:0)
$this->widget('ext.select2.ESelect2',array(
'name'=>'package_item',
'data'=>CHtml::listData(Package::model()->findAll(), 'id', 'package_item'), //the whole available list
'htmlOptions'=>array(
'placeholder'=>' search packge item?',
//'options'=>$options, //the selected values
'multiple'=>'multiple',
'style'=>'width:530px',
),
));
这样做了,现在它的工作。感谢god.Drop down创建,但它不可搜索,然后我注释掉jquery,现在它的工作。但我的下一个问题是如何在数据库中存储多个值?