dongxuanyi3406 2017-08-13 12:45
浏览 60
已采纳

Yii2创建数据行工作但更新没有

I saw red some answers on similar questions but still can't understand where is my problem. I have a _form.php which is used when data row is created and updated аlso. When i create data row it is OK but when it redirects me to return $this->redirect(['view', 'id' => $model->id]); but the data is not updated. Tried to var_dump($model->getErrors()) (as I saw in the answers of another question) but it returns me and empty array. These are my files: Controller action:

public function actionUpdate($id)
    {
        $model = $this->findModel($id);
        $settings = new Settings();

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            $languages = Lang::find()->all();
            foreach ($languages as $language) {
                if ($language->default != 1) {

                    $names = 'names_' . $language->url;
                    $varNames = Yii::$app->OutData->sanitize($model->$names);
                    $model->$names = $varNames;

                    $review = 'review_' . $language->url;
                    $varReview = Yii::$app->OutData->sanitize($model->$review);
                    $model->$review = $varReview;

                    $metaDesc = 'meta_desc_' . $language->url;
                    $varMetaDesc = Yii::$app->OutData->sanitize($model->$metaDesc);
                    $model->$metaDesc = $varMetaDesc;

                    $url = 'url_' . $language->url;
                    $varUrl = Yii::$app->OutData->sanitize($model->$url);
                    $model->$url = $varUrl;

                    $cBirth = 'country_birth_' . $language->url;
                    $varcBirth = Yii::$app->OutData->sanitize($model->$cBirth);
                    $model->$cBirth = $varcBirth;
                }
                else
                {
                    $model->names = Yii::$app->OutData->sanitize($model->names);
                    $model->review = Yii::$app->OutData->sanitize($model->review);
                    $model->meta_desc = Yii::$app->OutData->sanitize($model->meta_desc);
                    $model->url= Yii::$app->OutData->sanitize($model->url);
                    $model->country_birth = Yii::$app->OutData->sanitize($model->country_birth);
                }
            }

            //записване на изображенията + thumb
            if (isset($_POST["Author"]["imageFiles"]) and ! empty($_POST["Author"]["imageFiles"])) {

                $model->imageFiles = UploadedFile::getInstances($model, 'imageFiles');
                if (isset($model->imageFiles) and count($model->imageFiles) > 0) {
                    foreach ($model->imageFiles as $key => $file) {
                        $parseProdTitle = MakeURL::parseImageName($model->names.'_'.$model->id);
                        $fileName = $parseProdTitle . '_' . $model->id . '.' . $file->extension;
                        $fileName = Yii::$app->translate->cyr_to_lat($fileName);
                        $model->filename = $fileName;
                        $model->save(false);
                        $pic = Yii::getAlias('@frontend/web') . '/authors/thumb-270/' . $fileName;
                        $pic2 = Yii::getAlias('@frontend/web') . '/authors/' . $fileName;
                        $file->saveAs(Yii::getAlias('@frontend/web') . '/authors/' . $fileName);
                        $image = file_get_contents(Yii::getAlias('@frontend/web') . '/authors/' . $fileName);
                        file_put_contents($pic, $image);
                        $model->resizeImg($pic);
                        $settings->compress($pic, $pic, 90);
                        $settings->compress($pic2, $pic2, 90);
                    }
                }
            }

           if($model->update()){
               var_dump(1);die;
           }else{
               var_dump($model->getErrors());die;// it dumps here but it returns an empty array
           }

           if($model->validate()){
               var_dump(1);die;// it dumps here so validate is ok ( I guess )
           }else{
               var_dump($model->getErrors());die;
           }


            return $this->redirect(['view', 'id' => $model->id]);
        } else {
            return $this->render('update', [
                'model' => $model,
            ]);
        }
    }

And my model:

<?php

namespace backend\models;

use Yii;
use omgdef\multilingual\MultilingualBehavior;
use omgdef\multilingual\MultilingualQuery;
use kartik\helpers\Html;

/**
 * This is the model class for table "author".
 *
 * @property integer $id
 * @property integer $active
 * @property string $filename
 * @property integer $sort
 * @property data $birthday
 *
 * @property AuthorLang[] $authorLangs
 */
class Author extends \yii\db\ActiveRecord
{
    public $imageFiles;
    private $languages = array();

    public function __construct() {
        foreach(Yii::$app->params['languages'] as $langArr){
            $langParam = new Lang;
            $langParam->id = $langArr['id'];
            $langParam->url = $langArr['url'];
            $langParam->local = $langArr['local'];
            $langParam->name = $langArr['name'];
            $langParam->default = $langArr['default'];
            $langParam->active = $langArr['active'];
            $this->languages[] = $langParam;
        }
        parent::__construct();
    }

    public static function find()
    {
        return new MultilingualQuery(get_called_class());
    }

    public function behaviors()
    {
        $languagesArray = [];
        foreach($this->languages as $language){
            if($language->default){
                $defLang = $language->url;
            }
            $languagesArray[$language->local] = $language->name;
        }

        return [
            'ml' => [
                'class' => MultilingualBehavior::className(),
                'languages' => $languagesArray,
                //'languageField' => 'language',
                //'localizedPrefix' => '',
                //'requireTranslations' => false',
                //'dynamicLangClass' => true',
                //'langClassName' => PostLang::className(), // or namespace/for/a/class/PostLang
                'defaultLanguage' => $defLang,
                'langForeignKey' => 'author_id',
                'tableName' => "{{%authorLang}}",
                'attributes' => [
                    'names',
                    'review',
                    'meta_desc',
                    'url',
                    'country_birth',
                ]
            ],
        ];
    }

    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'author';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        $required = ['names', 'review', 'meta_desc', 'url', 'birthday', 'country_birth'];

        $this->checkLanguage([$required]);

        return [
            [['active', 'sort'], 'required'],
            [$required, 'required'],
            ['names', 'string', 'max' => 255],
            ['country_birth', 'string', 'max' => 255],
            ['review', 'string'],
            ['meta_desc', 'string', 'max' => 170],
            ['url', 'string', 'max' => 60],
            [['active', 'sort'], 'integer'],
            [['filename'], 'string'],
        ];
    }

    protected function checkLanguage($megaArr = [])
    {
        foreach ($this->languages as $language)
        {
            if($language->default != 1)
            {
                foreach ($megaArr as $fields)
                {
                    foreach ($fields as $field)
                    {
                        $field .= '_' . $language->url;
                    }
                }
            }
        }
    }

    public function changeActiveForm() {
        $active = "";
        if ($this->active == 1) {
            $active = 'checked="checked"';
        }
        return '<label class="switch switch-custom block mbn taCenter">
                <input type="checkbox" value="1" id="check_' . $this->id . '" name="field_types" class="legend-switch" ' . $active . ' onchange="changeStatusActive(' . $this->id . ', \'author\');"></input>
                <label data-off="' . Yii::t('app', 'Не') . '" data-on="' . Yii::t('app', 'Да') . '" for="check_' . $this->id . '"></label>
                <span></span>
            </label>';
    }

    public function getKartikImagesList() {
        $doctorImagesArr = array();
        $doctorImages = Author::find()->where('id = :id', [':id' => $this->id])->orderBy(['id' => SORT_ASC])->one();
        if(isset($doctorImages->filename) and $doctorImages->filename!="" and $doctorImages->filename!=Null) {
            $fileName = Yii::getAlias('@frontend/web') . "/authors/" . $doctorImages->filename;
            if (file_exists($fileName)) {
                $fileNameUrl = Yii::$app->urlManagerFrontend->baseUrl . "/authors/thumb-270/" . $doctorImages->filename;
                $doctorImagesArr[] = Html::img($fileNameUrl, ['class' => 'file-preview-image', 'style' => 'width: 350px;']) .
                    '<a href="javascript://" onclick="deleteAuthorImage(' . $this->id . ')"><span class="glyphicons glyphicons-bin"></span></a>';
            }
        }
        return $doctorImagesArr;
    }

    public function resizeImg($img) {
        $sz = getimagesize($img);
        $ratio = $sz[0] / $sz[1]; // w/h

        $w2 = Yii::$app->params['thumbswidth']; // thumb 1 width

        $image = new SimpleImage();

        $image->load($img);

        $image->resize($w2, round($w2 / $ratio));
        $image->save($img);
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'active' => Yii::t('app','app.Active' ),
            'filename' => Yii::t('app','app.Filename' ),
            'sort' => Yii::t('app','app.Sort' ),
            'country_birth' => Yii::t('app','app.Birth Country' ),
            'names' => Yii::t('app','app.Names' ),
            'meta_desc' => Yii::t('app','app.Meta Desc' ),
            'filename' => Yii::t('app','app.Image' ),
            'birthday' => Yii::t('app','app.Birthday' ),
            'imageFiles' => Yii::t('app','app.Image' ),
            'description' => Yii::t('app','app.Review' ),
        ];
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getAuthorLangs()
    {
        return $this->hasMany(AuthorLang::className(), ['author_id' => 'id']);
    }
}

I didn't post the _form.php because it is the same for both actions (create and update) and I think that the problem is not in it.If you need it will update my question immediately. Thank you in advance!

  • 写回答

1条回答 默认 最新

  • doufendi9063 2017-08-13 16:33
    关注

    For some reason it is possible that the update does not affect any row in the table. In this case the function return 0 .. for check this situation you should chek this this way

    http://www.yiiframework.com/doc-2.0/yii-db-activerecord.html#update()-detail

     if($model->update() !== false){
               var_dump(1);die;
           }else{
               var_dump($model->getErrors());die;// it dumps here but it returns an empty array
           }
    

    then, just for debugging, you could also try using $model->save(false) instead of $model->update() ... this way the $model is saved without regarding the validation rules ..

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 DS18B20内部ADC模数转换器
  • ¥15 做个有关计算的小程序
  • ¥15 MPI读取tif文件无法正常给各进程分配路径
  • ¥15 如何用MATLAB实现以下三个公式(有相互嵌套)
  • ¥30 关于#算法#的问题:运用EViews第九版本进行一系列计量经济学的时间数列数据回归分析预测问题 求各位帮我解答一下
  • ¥15 setInterval 页面闪烁,怎么解决
  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动