【问题标题】:yii2 how to get selected dropdown valueyii2如何获取选定的下拉值
【发布时间】:2015-11-21 17:08:24
【问题描述】:

我正在尝试做一个 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;

?>

【问题讨论】:

  • 所以您想按客户分组?并为值做一个 sum()
  • 是的,我可以按客户分组。但我想显示所选客户的总价值
  • 与您的问题无关,但使用字符串连接以外的其他技术编写where 条件:where(['customerName' =&gt; $chosen]) 之类的东西要好得多(而且您不会稍后获取 pwnd,因为有人利用了该 SQL 注入漏洞)
  • 好的。我会做的。谢谢@tarleb :)

标签: php mysql yii2 dropdown


【解决方案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>";

【讨论】:

  • 你可以用$chosen = isset($post['chosen']) ? $post['chosen'] : ''代替$chosen = Yii::$app-&gt;request-&gt;post('chosen', '')
  • 包装foreach 循环的if 语句不是必需的,可以在不改变行为的情况下删除。
【解决方案2】:

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

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

或在 Yii2 中:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-10-05
    • 1970-01-01
    • 2012-12-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多