Show only records created by currently logged in user

Hi, please come to my rescue. I have tried this for 2 weeks now and I seem not to get the solution.

I have user table and an Expense table

I have a relationship btwn these table via id in user table and user_id in expense table.

In my ExpenseSearch Model I have


namespace frontend\models;

use yii\base\Model;
use yii\data\ActiveDataProvider;
use frontend\models\Expense;

/**
 * ExpenseSearch represents the model behind the search form of `frontend\models\Expense`.
 */
class ExpenseSearch extends Expense
{
    /**
     * {@inheritdoc}
     */
    public function rules()
    {
        return [
            [['id', 'user_id', 'trans_ref', 'expense_amount'], 'integer'],
            [['description', 'expense_date', 'payment_method'], 'safe'],
        ];
    }

    /**
     * {@inheritdoc}
     */
    public function scenarios()
    {
        // bypass scenarios() implementation in the parent class
        return Model::scenarios();
    }

    /**
     * Creates data provider instance with search query applied
     *
     * @param array $params
     * @param string|null $formName Form name to be used into `->load()` method.
     *
     * @return ActiveDataProvider
     */
    public function search($params, $formName = null)
    {
        $query = Expense::find()->where(['user_id' => Yii::$app->user->identity->id]);;

        // add conditions that should always apply here

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

        $this->load($params, $formName);

        if (!$this->validate()) {
            // uncomment the following line if you do not want to return any records when validation fails
            // $query->where('0=1');
            return $dataProvider;
        }

        // grid filtering conditions
        $query->andFilterWhere([
            'id' => $this->id,
            'user_id' => $this->user_id,
            'trans_ref' => $this->trans_ref,
            'expense_amount' => $this->expense_amount,
            'expense_date' => $this->expense_date,
        ]);

        $query->andFilterWhere(['like', 'description', $this->description])
            ->andFilterWhere(['like', 'payment_method', $this->payment_method]);

        return $dataProvider;
    }
}

Index is as below

public function actionIndex()
    {
        $searchModel = new ExpenseSearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);


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

Where could I be going wrong.

Thanks in advance

Where could I be going wrong.

Thanks in advance

public function search($params, $formName = null)
    {
        $query = Expense::find();

        // add conditions that should always apply here

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

        $this->load($params, $formName);

        if (!$this->validate()) {
            // uncomment the following line if you do not want to return any records when validation fails
            // $query->where('0=1');
            return $dataProvider;
        }

    $query->andWhere('user_id = ' . Yii::$app->user->identity->id);


        // grid filtering conditions
        $query->andFilterWhere([
            'id' => $this->id,
            'user_id' => $this->user_id,
            'trans_ref' => $this->trans_ref,
            'expense_amount' => $this->expense_amount,
            'expense_date' => $this->expense_date,
        ]);

        $query->andFilterWhere(['like', 'description', $this->description])
            ->andFilterWhere(['like', 'payment_method', $this->payment_method]);

        return $dataProvider;
    }
}

here an example: models/ArticuloSearch.php · master · Jonathan Morales / blog-yii-2-bootstrap-3 · GitLab

Hey mate

This still didn’t work for me

Oh geez, okay…

Uhhh, first thing, you gotta make sure those attribute types are right, ya know?

So in your rules you got:

[['id', 'user_id', 'trans_ref', 'expense_amount'], 'integer'],

But, like, is trans_ref really a number? Usually trans-refs are, I dunno, these crazy mixes of letters and numbers, not just plain old integers. Same thing with expense_amount—like, aren’t those decimal numbers? Like, money isn’t usually just whole numbers, man!

If you say these are integers but they’re not, the whole validation thing is gonna fail and your filters won’t work.

You got:

$query = Expense::find()->where(['user_id' => Yii::$app->user->identity->id]);

Which is good, ’cause you only wanna see your own expenses, right?
But then later you do:

$query->andFilterWhere([
    'id' => $this->id,
    'user_id' => $this->user_id,  // uh oh, this might mess stuff up
    // ...
]);

And that’s a problem because $this->user_id is coming from the filter form, which could mess with your original filter or even be empty.

So, like, you gotta just remove this line:

//'user_id' => $this->user_id,

Because you already filtered by logged-in user, Woop-woop! Don’t go filterin’ twice or you’ll confuse the system, and that’s not good.

Finally, if your filters just aren’t working and you don’t get any errors — Maybe validation is failing and you don’t even know!

Try this, man:

if (!$this->validate()) {
    \Yii::info($this->errors);
    return $dataProvider;
}

This way you can see what’s wrong and fix it before your app stops showing data.

1 Like