我正在尝试做一个 Yii2 应用程序。
我在 mysql 中有“customerID”、“customerName”和“total”列。
我想向用户展示选定客户对用户的总值(value)。
例如。
Customer 1 = 100
Customer 2 = 250
Customer 3 = 300
Customer 1 = 300
Customer 3 = 500
所以。如果用户在我的下拉列表中选择客户 3 我想向用户展示 300+ 500 = 800。
我可以查看特定客户的总列总和。 但我无法获得所选客户的总列的总和
我该怎么做?
这是我的代码。
<?php $form = ActiveForm::begin(); ?>
<?php $chosen = ""; ?>
<?= $form->field($model, 'customerName')->dropDownList(
ArrayHelper::map(Siparisler::find()
->all(),'customerName','customerName'),
[
'prompt'=>'Chose a Customer'
]
);
$var = ArrayHelper::map(Siparisler::find()->where("(customerName = '$chosen' )")->all(),'total','total');
echo "<h3><br>"."Total"."<br><h3>";
$sum = 0;
foreach($var as $key=>$value)
{
$sum+= $value;
}
echo $sum;
?>
最佳答案
试试这个。这些应该在您的 Controller 的操作中
public function actionTotal() {
//you've use $chosen for selected customer in drop down list
$chosen = Yii::$app->request->post('chosen', '');
// select all customer data based on $chosen
$customers = Siparisler::find()->where(['=', 'customerName', $chosen])
->all();
$sum = 0;
foreach($customers as $k=>$customer)
{
$sum += $customer->total;
}
return $this->render('total', [
'sum' => $sum,
'customers' => $customers,
]);
}
下面的代码应该是您的 View
$form = ActiveForm::begin();
// i use yii\helpers\Html
Html::dropDownList('chosen', ArrayHelper::map(Siparisler::find()->all(), 'customerName', 'customerName'),
[
'prompt'=>'Chose a Customer'
]);
Html::submitButton('Submit');
ActiveForm::end();
echo "<h3><br>" . "Total" . "<br>" . $sum . "<h3>";
关于php - yii2 如何获取选定的下拉值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33846185/