S
S
Svetlana Galenko2019-01-26 11:44:23
Yii
Svetlana Galenko, 2019-01-26 11:44:23

Why is the record not saved after the user has set up their account?

Greetings, there is a user account on the site, it can be configured. Namely, change and add the first name, last name, country, phone number, gender and date of birth. But after the user has registered everything he needs, his settings are not saved in the account, and the inscription 'Settings successfully saved' does not appear, they were not saved in the database either .. I apparently missed something in the code .. Please help ..
Here is a screenshot of the settings, what exactly I want..
5c4c0f628d96a618190231.png
Here is the structure of my database:
5c4c0f8a7556c848479737.png
In this controller, the settings are connected, which, in theory, should have been saved on the "profile" page:
ProfileController.php:

<?php

namespace app\controllers\user;

use app\components\Controller;
use app\helpers\UserSettingHelper;
use app\models\User;
use yii\data\Pagination;
use yii\helpers\ArrayHelper;
use yii\web\NotFoundHttpException;

class ProfileController extends Controller
{
    public function actionIndex()
    {
        $this->layout = 'page';
        $vars = [];

        $user = User::find()->where(['username' => $_GET['username']])->one();
        if ($user === null)
            throw new NotFoundHttpException();

        $setting = UserSettingHelper::get($user);

        $vars = ArrayHelper::merge($vars, [
            'user' => $user,
            'setting' => $setting,
        ]);

        return $this->render('index', $vars);
    }
}

Next is the page for saving the SettingsController.php settings:
<?php

namespace app\controllers\user;

use app\components\Controller;
use app\helpers\UserSettingHelper;
use app\models\forms\SettingPageSaveForm;
use app\models\forms\SettingSecuritySaveForm;
use yii\filters\AccessControl;

class SettingController extends Controller
{
    public function behaviors()
    {
        return [
            'access' => [
                'class' => AccessControl::className(),
                'rules' => [
                    [
                        'allow' => true,
                        'roles' => ['@'],
                    ],
                ],
            ],
        ];
    }

    public function actionIndex()
    {
        $this->layout = 'page';

        $setting = UserSettingHelper::get(\Yii::$app->user->identity);

        $page = new SettingPageSaveForm();
        $page->setAttributes($setting->attributes, true);
        if ($page->load(\Yii::$app->request->post())) {
            $page->saveSettings(\Yii::$app->user->identity);
        }

        $security = new SettingSecuritySaveForm();
        $security->setAttributes($setting->attributes, true);
        if ($security->load(\Yii::$app->request->post())) {
            $security->saveSettings(\Yii::$app->user->identity);
        }

        return $this->render('index', [
            'page' => $page,
            'security' => $security,
            'setting' => $setting,
        ]);
    }
}

Next, connecting the UserSettingHelper.php components:
<?php

namespace app\helpers;

use app\models\User;
use app\models\UserSetting;
use yii\helpers\Html;

class UserSettingHelper
{
    public static function get(User $user)
    {
        return UserSetting::find()->where([
            'user_id' => $user->id,
        ])->one();
    }

    public static function getAvatar(UserSetting $setting)
    {
        return $setting->avatar == '' ? '/images/page-avatar.png' : '/uploads/' . $setting->avatar;
    }

    public static function getFirstname(UserSetting $setting)
    {
        return Html::encode($setting->firstname);
    }

    public static function getName(UserSetting $setting)
    {
        return Html::encode($setting->name);
    }

    public static function getPhone(UserSetting $setting)
    {
        return Html::encode($setting->phone);
    }

}

Settings saving model SettingPageSaveForm.php
<?php
namespace app\models\forms;

use app\models\User;
use app\models\UserSetting;

class SettingPageSaveForm extends UserSetting
{
    public function scenarios()
    {
        return [
            self::SCENARIO_DEFAULT => ['name', 'firstname', 'country', 'phone', 'gender', 'birth_day', 'birth_month', 'birth_year']
        ];
    }

    public function saveSettings(User $user)
    {
        if (!$this->validate()) {
            \Yii::$app->getSession()->setFlash('warning', implode('<br />', $this->getFirstErrors()));
            return false;
        }

        $setting = UserSetting::find()->where([
            'user_id' => $user->id,
        ])->one();

        $setting->setAttributes([
            'name' => $this->name,
            'firstname' => $this->firstname,
            'country' => $this->country,
            'phone' => $this->phone,
            'gender' => $this->gender,
            'birth_day' => $this->birth_day,
            'birth_month' => $this->birth_month,
            'birth_year' => $this->birth_year
        ]);
        
        $setting->update(false);
        \Yii::$app->getSession()->setFlash('success', \Yii::t('app', 'Настройки успешно сохранены'));
    }
}

And here is the UserSetting.php itself, where all the settings are registered:
<?php
namespace app\models;

use yii\db\ActiveRecord;

class UserSetting extends ActiveRecord
{
    const AUTH_CONFIRM_DISABLED = 0;
    const AUTH_CONFIRM_ENABLED = 1;

    const GENDER_UNKNOWN = 0;
    const GENDER_MALE = 1;
    const GENDER_FEMALE = 2;

    const COUNTRY_ABHAZIYA = 0;
    const COUNTRY_AVSTRALIYA = 1;

    public static function tableName()
    {
        return '{{%user_setting}}';
    }

    public function rules()
    {
        return [
            ['user_id', 'integer'],
            ['auth_confirm', 'in', 'range' => [self::AUTH_CONFIRM_ENABLED, self::AUTH_CONFIRM_DISABLED]],
            ['name', 'string', 'length' => [0, 255]],
            ['firstname', 'string', 'length' => [0, 255]],
            ['phone', 'match', 'pattern' => '/^\+7\s\([0-9]{3}\)\s[0-9]{3}\-[0-9]{2}\-[0-9]{2}$/', 'message' => ' Что-то не так'],
            ['gender', 'in', 'range' => array_keys(self::getGenderArray())],

            [['birth_day', 'birth_month', 'birth_year', 'country'], 'integer'],
            ['birth_day', 'in', 'range' => array_keys(self::getBirthDayArray())],
            ['birth_month', 'in', 'range' => array_keys(self::getBirthMonthArray())],
            ['birth_year', 'in', 'range' => array_keys(self::getBirthYearArray())],
            ['country', 'in', 'range' => array_keys(self::getCountryArray())],
            ['friends_limit', 'integer'],
        ];
    }

    public function attributeLabels()
    {
        return [
            'user_id' => 'ID',
            'name' => \Yii::t('app', 'Имя'),
            'firstname' => \Yii::t('app', 'Фамилия'),
            'country' => \Yii::t('app', 'Страна'),
            'phone' => \Yii::t('app', 'Номер телефона'),
            'auth_confirm' => \Yii::t('app', 'Подтверждение авторизации'),
            'avatar' => \Yii::t('app', 'Аватар'),
            'status' => \Yii::t('app', 'Статус'),
            'info' => \Yii::t('app', 'Информация'),
        ];
    }

    public function getUser()
    {
        return $this->hasOne(User::className(), ['id' => 'user_id']);
    }

    public function getCountryString()
    {
        $countries = self::getCountryArray();
        return isset($countries[$this->country]) ? $countries[$this->country] : '';
    }

    public function getCountryArray()
    {
        return [
        self::COUNTRY_ABHAZIYA => \Yii::t('app', 'Абхазия'),
        self::COUNTRY_AVSTRALIYA => \Yii::t('app', 'Автралия'),
        ];
    }

    public function getGenderString()
    {
        $genders = self::getGenderArray();
        return isset($genders[$this->gender]) ? $genders[$this->gender] : '';
    }

    public static function getGenderArray()
    {
        return [
            self::GENDER_UNKNOWN => \Yii::t('app', ''),
            self::GENDER_MALE => \Yii::t('app', 'мужской'),
            self::GENDER_FEMALE => \Yii::t('app', 'женский'),
        ];
    }

    public static function getBirthYearArray()
    {
        $array = [
            '0' => ''
        ];
        for ($i = 1901; $i < 2004; $i++) {
            $array[$i] = $i;
        }
        return $array;
    }

    public static function getBirthDayArray()
    {
        $array = [
            '0' => ''
        ];
        for ($i = 1; $i <= 31; $i++) {
            $array[$i] = $i;
        }
        return $array;
    }

    public static function getBirthMonthArray()
    {
        return [
            0 => '',
            1 => \Yii::t('app', 'января'),
            2 => \Yii::t('app', 'февраля'),
            3 => \Yii::t('app', 'марта'),
            4 => \Yii::t('app', 'апреля'),
            5 => \Yii::t('app', 'мая'),
            6 => \Yii::t('app', 'июня'),
            7 => \Yii::t('app', 'июля'),
            8 => \Yii::t('app', 'августа'),
            9 => \Yii::t('app', 'сентября'),
            10 => \Yii::t('app', 'октября'),
            11 => \Yii::t('app', 'ноября'),
            12 => \Yii::t('app', 'декабря'),
        ];
    }

    public function getBirthDateString()
    {
        if ($this->birth_day != '0' && $this->birth_month != '0' && $this->birth_year != '0') {
            return $this->birth_day . ' ' . self::getBirthMonthArray()[$this->birth_month] . ' ' . $this->birth_year;
        }
        return false;
    }
}

Answer the question

In order to leave comments, you need to log in

[[+comments_count]] answer(s)
M
morricone85, 2019-01-26
@swallow_97

the first thing that caught my eye was the ProfileController class:
public function actionIndex()
{
$this->layout = 'page';
$vars = [];
$user = User::find()->where(['username' => $_GET['username']])->one();
....
}
$_GET['username'] - what do you have?
Why does this data go to the index method and not, say, to the view method?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question