Reputation: 31
I'm new to YII framework, I want to filter my data on the frontend using product, month and year dropdown. Here is what I have in my controller
<?php
public function actionProducts()
{
$sql = "SELECT product, cost, supplier, month, year
FROM products
WHERE year = :year
GROUP BY product, month, year";
$product = Data::findBySql($sql, [':year' => 2022])->asArray()->all();
$response = ['data' => $product];
header('Content-Type: application/json');
return json_encode($response, JSON_NUMERIC_CHECK);
?>
How do I approach this?
Upvotes: 1
Views: 257
Reputation: 3762
First, make your query parameter part of the function definition:
<?php
public function actionProducts($product, $month, $year)
{
$sql = "SELECT product, cost, supplier, month, year
FROM products
WHERE year = :year AND month=:month AND year=:year
GROUP BY product, month, year";
$product = Data::findBySql($sql, [
':year' => $year, ':month'=>$month, ':product'=>$product
])->asArray()->all();
Second, JSON responses are fully supported by Yii including array conversion:
\Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
return ['data' => $product];
}
Upvotes: 1