2017-08-13 48 views
0

我看到紅色在類似問題上的一些答案,但仍不明白我的問題在哪裏。我有一個_form.php這是在創建和更新數據行時使用的。當我創建數據行時,它是確定的,但是當它將我重定向到return $this->redirect(['view', 'id' => $model->id]);但數據未更新。試圖var_dump($model->getErrors())(正如我在另一個問題的答案中看到的),但它返回我並且爲空array。 這些都是我的文件: 控制器動作:Yii2創建數據行工作,但更新不

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, 
      ]); 
     } 
    } 

而且我的模型:

<?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']); 
    } 
} 

我沒有貼_form.php,因爲它是這兩個動作是相同的(創建和更新)和我認爲問題不在其中。如果您需要,它會立即更新我的問題。先謝謝你!

回答

1

由於某些原因,更新可能不會影響表中的任何行。在這種情況下,函數返回0。對於檢查這種情況下,你應該赤本這樣

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 
     } 

那麼,只是爲了調試,你也可以嘗試使用$model->save(false)代替$model->update() ......這$模型的保存方式不涉及驗證規則。

+0

嘗試使用您發佈的條件並將其放入'if'部分。所以它返回1.也嘗試了'$ model-> save(false)',但是再次沒有。我很困惑。如果硬編碼它會有多大的錯誤?像'Yii :: $ app-> db-> createCommand(query,[params]) - > execute()'。 –

+1

這意味着更新中不涉及行..? 。爲什麼? 。你確定你以前沒有保存模型(沒有改變)? ..無論如何如果你沒有其他選擇,你甚至可以用createCommand來嘗試......沒有什麼問題......然而,奇怪的是,更新沒有完成。 – scaisEdge

+0

找到了!非常感謝你這行'你確定你沒有保存模型(沒有改變)':D之前! '$ model-> update()'之前真的有另一個'$ model-> save()'。 –