簡體   English   中英

yii2如何獲得選定的下拉值

[英]yii2 how to get selected dropdown value

我正在嘗試做一個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;

?>

嘗試這個。 這些應該在您的控制器的動作中

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

除了David的答案外:在純SQL中也可以對列求和。 這可以使您免於不必要的PHP復雜性(我會盡可能避免使用ArrayHelper::map )。 該查詢將是

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

或在Yii2中:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM