How can I pass parameter/dropdown value to model function

1.2k views Asked by At

I am using yii2 advanced template improved

Not sure if relevant to problem/a solution but to get to the category I have a form with some javascript which on change redirects the user to the category selected.

I have the following code which allows me to access the posts within that category id I go to localhost:8888/advanced/article/category?id=1

The problem at the minute is that if I call getCategoryName function in my model from my category view the id parameter isn't being passed to the model function therefore when using getCategoryName defaults to sport.

 public function actionCategory($id)
{

    $model = new Article();

    $searchModel = new ArticleSearch();

    $query = Article::find()
    ->where(['category' => $id]);

     $dataProvider = new ActiveDataProvider([
                    'query' => $query,
                    ]);

    return $this->render('category', [
        'searchModel' => $searchModel,
        'dataProvider' => $dataProvider,
        'model'=>$model,
    ]);
}

Then within my view I use the following which works to an extent in terms of executing the model function, however I am unsure on how to pass the parameter/current category id to the model function. The below code work for the _index & in the single article view.

<?= $model->CategoryName ?>

This is my model function

public function getCategoryName($category = null)
{
    $category = (empty($category)) ? $this->category : $category ;

    if ($category === self::CATEGORY_ECONOMY)
    {
        return Yii::t('app', 'Economy');
    }
    elseif ($category === self::CATEGORY_SOCIETY)
    {
        return Yii::t('app', 'Society');
    }
    else
    {
        return Yii::t('app', 'Sport');
    }
}
2

There are 2 answers

3
RN Kushwaha On

Use something like this, in your view

$request = Yii::$app->request;
$id = $request->get('id');//get id from request or change according to your requirement
echo  $model->getCategoryName($id);//full method name here
0
Serghei Leonenco On

Try to use this. change === to ==:

public function getCategoryName($category = null)
{
    $category = (empty($category)) ? $this->category : $category ;

    if ($category == self::CATEGORY_ECONOMY)
    {
        return Yii::t('app', 'Economy');
    }
    elseif ($category == self::CATEGORY_SOCIETY)
    {
        return Yii::t('app', 'Society');
    }
    else
    {
        return Yii::t('app', 'Sport');
    }
}