【发布时间】:2017-01-28 17:11:08
【问题描述】:
我在 yii2 中做我的项目。 我有从 db 获取数据到下拉列表的表单(使用 kartik depdtop 小部件)。 第一个字段是“type_of_goods”,取决于“type_of_goods”客户收到“货物”。 之后是“goods_amount”和“total_cost”的两个文本输入字段,商品取决于“goods_amount”(goods_amount * price)。
客户输入他想购买的商品数量,或者他想购买的金额,js脚本在这两种情况下都会在另一个字段中显示他的价值。
价格值在数据库中的商品表中。 我可以从“商品”字段中获取商品 ID 或有关商品的一些信息(以执行数据库查询并获取价格并将其放入 js 函数中),或者甚至可以将价格放入执行我上面写的事情的 js 脚本中。
我怎样才能意识到这一点?这是正确的做法吗?
代码: 查看
<?php $form = ActiveForm::begin([
'options' => [
'class' => 'form-horizontal col-lg-11',
'enctype' => 'multipart/form-data'
],
]); ?>
<?= $form->field($type_of_goods, 'id')
->dropDownList(
ArrayHelper::map(Type_of_goods::find()->all(), 'id', 'name'),
['id'=>'type_of_goods_id']
);
?>
<?= $form->field($goods, 'id')->widget(DepDrop::classname(), [
'options' => ['id' => 'id'],
'pluginOptions' => [
'depends' => ['type_of_goods_id'],
'placeholder' => 'Choose your goods',
'url' => \yii\helpers\Url::to(['goods/goods-dep-type'])
]
]);
?>
<?= $form->field($goods, 'price')->textInput();
?>
<?= $form->field($order, 'amount')->textInput();
?>
<?php ActiveForm::end(); ?>
控制器:
public function actionGoodsDepType()
{
$out = [];
if (isset($_POST['depdrop_parents'])) {
$parents = $_POST['depdrop_parents'];
if ($parents != null) {
$game_id = $parents[0];
$out = \app\models\Goods::gelGoodsList($goods_type_id);
echo Json::encode(['output' => $out, 'selected' => '']);
return;
}
}
echo Json::encode(['output' => '', 'selected' => '']);
}
型号:
public static function gelGoodsList($type_id)
{
$query = self::find()
->where(['type_id' => $type_id])
->select(['id', 'name'])->asArray()->all();
return $query;
}
public static function getPrice($id)
{
$query = self::find()
->where(['id' => $id])
->select(['price'])->asArray()->one();
return $query;
}
【问题讨论】: