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' => 2018])->asArray()->all();
$response = ['data' => $product];
header('Content-Type: application/json');
return json_encode($response, JSON_NUMERIC_CHECK);
?>
How do I approach this?
evstevemd
(Stefano Mtangoo)
2
First make use of yii\rest\Controller class. It does a lot for you. See Restful services. That being said, here is how
<?php
use yii\data\ActiveDataProvider;
class ProductsController extends \yii\rest\Controller
{
public function actionProducts($product = null, $month = null, $year = null)
{
$query = Product::find()->filterWhere(['month' => $month, 'product' => $product, 'year' => $year]);
return new ActiveDataProvider([
'query' => $query,
//sert others like sorting and pagination
]);
}
}
Make sure front end passes whatever filter as query param in this case
softark
(Softark)
3
Indeed!
@jasperking18
Take enough time for you to read through the guide. It’s worth doing.
Make haste slowly.