yii2如何获取选定的下拉值

时间:2015-11-21 17:08:24

标签: php mysql yii2 dropdown

我正在尝试使用Yii2。

我在mysql中有'customerID','customerName'和'total'列。

我想向用户显示所选客户的总价值。

例如。

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;

?>

2 个答案:

答案 0 :(得分:1)

试试这个。这些应该在你的控制器的行动中

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,
    ]);
}

以下这些代码应该是您的观点

$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>";

答案 1 :(得分:0)

除了David的回答:对列进行求和也可以在纯SQL中完成。这可能会使您免于一些不必要的PHP复杂性(我尽量避免使用ArrayHelper::map)。对此的查询将是

SELECT
  sum(total) as sumTotal
FROM customer
WHERE customerName = '<NAME>';

或在Yii2中:

Siparisler::find()->where(['customerName' => $chosenName])->sum('total');