abilham
(Andrewbilham)
1
Evening,
I am trying to create a dependent dropdown.
The table structure
Parts -> Suppliers (‘company_name’) -> Supplier parts (‘cost_price’)
but what i would like to do is create a dropdown based on part ID from first drop down but display Supplier and cost in the second drop down.
how would i convert this from the first dropdown or is their a better way to do it?
$query = new \yii\db\Query;
$query->select(['id,concat(name, " " ,description) AS text'])
->from('parts')
->where(['like','description',$q])
->orwhere(['like','name',$q])
->limit(20);
$command = $query->createCommand();
$data = $command->queryAll();
Bizley
(Bizley)
2
abilham
(Andrewbilham)
3
Thank you.
that is where i had started but cant seem to get it working!
my view:
$url = \yii\helpers\Url::to(['partlist']);
echo $form->field($model, 'part_id')->label("Select Part")->widget(Select2::classname(), [
//'initValueText' => $partDesc, // set the initial display text
'options' => ['placeholder' => 'Select a Part ...'],
'class' => 'part_list',
'id' => 'cat-id',
'pluginOptions' => [
'language' => [
'errorLoading' => new JsExpression("function () { return 'Waiting for results...'; }"),
],
'tags' => true,
'tokenSeparators' => [','],
'maximumInputLength' => 10,
'ajax' => [
'url' => $url,
'dataType' => 'json',
'data' => new JsExpression('function(params) { return {q:params.term}; }'),
],
],
'pluginEvents' => [
"change" => 'function() {
if(isNaN(this.value)){
$("#newpartbtn").show();
}else{
$("#newpartbtn").hide();
}
}',
],
]);
?>
<?php
$url1 = \yii\helpers\Url::to(['subcat']);
echo $form->field($model, 'supplier_id')->widget(DepDrop::classname(), [
'options'=>['id'=>'subcat-id'],
'pluginOptions'=>[
'depends'=>['cat-id'],
'placeholder'=>'Select...',
'url'=>Url::to(['subcat'])
]
]);
?>
And controller:
public function actionPartlist($q = null, $id = null) {
\Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
$out = ['results' => ['id' => '', 'text' => '']];
if (!is_null($q)) {
$query = new \yii\db\Query;
$query->select(['id,concat(name, " " ,description) AS text'])
->from('parts')
->where(['like','description',$q])
->orwhere(['like','name',$q])
->limit(20);
$command = $query->createCommand();
$data = $command->queryAll();
$out['results'] = array_values($data);
}
elseif ($id > 0) {
$out['results'] = ['id' => $id, 'text' => parts::find($id)->description];
}
return $out;
}
public function actionSubcat() {
Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
$out = [];
if (isset($_POST['depdrop_parents'])) {
$parents = $_POST['depdrop_parents'];
if ($parents != null) {
$cat_id = $parents[0];
$out = self::getSubCatList($cat_id);
// the getSubCatList function will query the database based on the
// cat_id and return an array like below:
// [
// ['id'=>'<sub-cat-id-1>', 'name'=>'<sub-cat-name1>'],
// ['id'=>'<sub-cat_id_2>', 'name'=>'<sub-cat-name2>']
// ]
return ['output'=>$out, 'selected'=>''];
}
}
return ['output'=>'', 'selected'=>''];
}