/** * @param integer - $id_user user id for whom will be get interests * @param bool - $with_title - if true - result array will be has as value - title from Interest table, otherwise - id_interest * @return array of user interest */ public static function getUserInterest($id_user, $with_title = false) { $models_arr = self::find()->where(['id_user' => $id_user])->asArray()->all(); $result_array = ArrayHelper::getColumn($models_arr, 'id_interest'); // for with_title mode - replace id to title from Interest model if ($with_title) { // get all interests $all_interest_arr = Interest::getInterestAsArray(); $result_array = array_map(function ($value) use($all_interest_arr) { if (empty($all_interest_arr[$value])) { // it's almost impossible, anyway handle this situation return ''; } else { return $all_interest_arr[$value]; } }, $result_array); } return $result_array; }
/** * Updates an existing User model. * If update is successful, the browser will be redirected to the 'view' page. * @param integer $id * @return mixed */ public function actionUpdate($id) { // find user model $model = $this->findModel($id); // create user interests model $user_interest_model = new UserInterest(); $post_arr = Yii::$app->request->post(); if ($model->load($post_arr) && $user_interest_model->load($post_arr) && $model->save()) { $user_interest_model->updateInterests(); return $this->redirect(['index']); } else { // get whole array of interest (for making a choice in update view) $interest_arr = Interest::getInterestAsArray(); // get array of interest that user already choose $checked_interest_arr = UserInterest::getUserInterest($id); // set chosen interest $user_interest_model->id_interest = $checked_interest_arr; $user_interest_model->id_user = $id; return $this->render('update', ['model' => $model, 'user_interest_model' => $user_interest_model, 'interest_arr' => $interest_arr]); } }