您现在的位置是:首页 > 站长学院 > PHP教程 > PHP教程

activerecord – 更新Yii 2中的记录

编辑:站长来源:网络整理作者: 未知2020-12-13PHP教程

简介潜入这个新的yii 2,我已经卡住了.我尝试用表单更新用户记录.原始记录正在表单中加载,但更改表单中的值不会更新记录. public function actionUserprofile(){ $id = Yii::$app-user-identity-id; $model = User::find()-where(['id' = $id])-one(); if($model-

潜入这个新的yii 2,我已经卡住了.我尝试用表单更新用户记录.原始记录正在表单中加载,但更改表单中的值不会更新记录.

public function actionUserprofile()
{
    $id = Yii::$app->user->identity->id;
    $model = User::find()->where(['id' => $id])->one();

    if($model->load(Yii::$app->request->post()) && $model->save())
    {
        Yii::$app->session->setFlash('success','You have updated your profile.');

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



}

//view form
<div>

<?php $form = ActiveForm::begin(); ?>
<?= $form->field($model,'username')->textInput(['maxlength' => 255]) ?>
<?= $form->field($model,'first_name')->textInput(['maxlength' => 255]) ?>
<?= $form->field($model,'last_name')->textInput(['maxlength' => 255]) ?>
<div class="form-group">
    <?= Html::submitButton('Submit',['class'=>'btn btn-success']) ?>
</div>
<?php ActiveForm::end(); ?>

解决方法

如果您使用此模型,请使用此 https://github.com/yiisoft/yii2-app-advanced/blob/master/common/models/User.php

您可以像这样创建类Profile:

<?php
namespace frontend\models;
use common\models\User;
use yii\base\Model;
use Yii;
/**
 * Signup form
 */
class Profile extends Model
{
    public $username;
    public $first_name;
    public $last_name;
    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            ['username','filter','filter' => 'trim'],['username','required'],'unique','targetClass' => '\common\models\User','message' => 'This username has already been taken.'],'string','min' => 2,'max' => 255],[['first_name','last_name'],];
    }
    /**
     * Signs user up.
     *
     * @return User|null the saved model or null if saving fails
     */
    public function profileSave()
    {
        if ($this->validate()) {
            $user = User::findOne(Yii::$app->user->id);
            $user->username = $this->username;
            $user->first_name = $this->first_name;
            $user->last_name = $this->last_name;

            if ($user->save()) {
                return $user;
            }
        }
        return null;
    }
}

并改变控制器

$model = User::find()->where(['id' => $id])->one();
if($model->load(Yii::$app->request->post()) && $model->save())

$model = new Profile();
if($model->load(Yii::$app->request->post()) && $model->profileSave())

很赞哦! ()

点击排行

本栏推荐

猜你喜欢