简体   繁体   English

yii2如何获得选定的下拉值

[英]yii2 how to get selected dropdown value

I am trying to do a Yii2 application. 我正在尝试做一个Yii2应用程序。

I have 'customerID', 'customerName' and 'total' column in mysql. 我在mysql中有“ customerID”,“ customerName”和“ total”列。

I want to show user to selected customers's total value to user. 我想向用户显示所选客户对用户的总价值。

For Example. 例如。

Customer 1 = 100
Customer 2 = 250
Customer 3 = 300
Customer 1 = 300
Customer 3 = 500

So. 所以。 If user choose Customer 3 in my dropdownlist I want to show user to 300+ 500 = 800. 如果用户在我的下拉列表中选择“客户3”,我想向用户显示300+ 500 = 800。

I can see the sum of total columns for specific customer. 我可以看到特定客户的总计列的总和。 But I cant get the sum of total columns of selected customer 但是我无法获得所选客户的总列数之和

How can I do this? 我怎样才能做到这一点?

This is my code below. 这是我的下面的代码。

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

?>

try this. 尝试这个。 These should be in your controller's action 这些应该在您的控制器的动作中

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

these code below should be your 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>";

In addition to David's answer: Summing over a column can also be done in pure SQL. 除了David的答案外:在纯SQL中也可以对列求和。 This might save you from some unwanted PHP complexity (I try to avoid ArrayHelper::map whenever I can). 这可以使您免于不必要的PHP复杂性(我会尽可能避免使用ArrayHelper::map )。 The query for this would be 该查询将是

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

or in Yii2: 或在Yii2中:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM