почему при обновлении данные сохраняются а при добавлении нет yii2?

Общие вопросы по использованию второй версии фреймворка. Если не знаете как что-то сделать и это про Yii 2, вам сюда.
Ответить
die1990
Сообщения: 15
Зарегистрирован: 2021.12.21, 20:18

почему при обновлении данные сохраняются а при добавлении нет yii2?

Сообщение die1990 »

Добрый вечер уважаемые. Голова взрывается просто....

По урокам писал админскую часть блога, все было хорошо, пока не дошло до установки дополнений и виджетов, а именно загрузка файлов и визуального редактора. Хотя уверен дело не в нем, но в чем, не понятно.

Когда обновляю существующую запись, все хорошо проходит и сохраняется, и текст, и теги и картинка... Но когда Хочу новую запись добавлять, страница просто перезагружается и показывает данные, которые я вводил , видимо я залетаю вот сюда

Код: Выделить всё

   else {
            $model->loadDefaultValues();
        }
в actionCreate. Но понять не могу, почему, ни ошибок, ничего нет. Ладно бы обновление не работало бы, понять можно было, что что то не так.....

модель Article

Код: Выделить всё

 <?php
 
namespace app\models;
 
use Yii;
use yii\helpers\ArrayHelper;
use yii\web\UploadedFile;
 
/**
 * This is the model class for table "article".
 *
 * @property int $id
 * @property string $title
 * @property string $description
 * @property string $keywords
 * @property string $metaDescription
 * @property string $content
 * @property string $image
 * @property int $viewed
 * @property int $user_id
 * @property int $category_id
 * @property string $dateSave
 */
class Article extends \yii\db\ActiveRecord
{
    public $tags_array;
    public $keys_array;
    public $file;
 
    /**
     * {@inheritdoc}
     */
    public static function tableName()
    {
        return 'article';
    }
 
    /**
     * {@inheritdoc}
     */
    public function rules()
    {
        return [
            [['title', 'description', 'content','metaDescription', 'category_id','keywords'], 'required'],
            [['title', 'description', 'content','metaDescription', 'category_id','keywords'], 'string'],
            [['dateSave'], 'date', 'format'=>'php:M j, Y'],
            [['dateSave'], 'default', 'value'=>date('M j, Y')],
            [['title','keywords'], 'string', 'max'=>255],
            [['image'], 'default', 'value' => 'images/no-image.png'],
            [['tags_array', 'keys_array', 'image', 'file'], 'safe'],
//            [['file'], 'image']
        ];
    }
 
    /**
     * {@inheritdoc}
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'title' => 'Наименование',
            'description' => 'Описание',
            'keywords' => 'Ключевые слова',
            'metaDescription' => 'Мета описание',
            'content' => 'Текс статьи',
            'image' => 'Картинка',
            'viewed' => 'Просмотры',
            'user_id' => 'ID пользователя',
            'category_id' => 'Категория',
            'dateSave' => 'Дата создания',
            'tags' => 'Тэги',
            'tags_array' => 'Тэги',
            'keys_array' => 'ключевые слова',
            'file' => 'Загрузка изображения'
        ];
    }
 
    public static function randomArticle(){
        return Article::find()->limit(3)->orderBy('RAND()')->all();
    }
 
 
 
    public function clearCurrentTags(){
        ArticleTag::deleteAll(['article_id'=>$this->id]);
    }
 
    public function clearCurrentKeys(){
        ArticlesKeys::deleteAll(['article_id'=>$this->id]);
    }
 
//    public function deleteImage(){
//        $imageUploadModel = new imageUpload();
//        $imageUploadModel->deleteCurrentImage($this->image);
//    }
 
 
//    public function saveImage($fileName){
//        $this->image = $fileName;
//        return $this->save(false);
//    }
 
    public function saveCategory($category_id){
        $category = Category::findOne($category_id);
        if($category != null){
            $this->link('category', $category);
            return true;
        }
    }
 
    public function saveTags(){
        if(is_array($this->tags_array)){
            $oldTags = ArrayHelper::map($this->tags, 'name', 'id');
            foreach ($this->tags_array as $oneNewTag){
                if(isset($oldTags[$oneNewTag])){
                    unset($oldTags[$oneNewTag]);
                }else{
                    $this->createNewTag($oneNewTag);
                }
            }
            ArticleTag::deleteAll(['and', ['article_id'=>$this->id], ['tag_id'=>$oldTags]]);
        }
        else{
            $this->clearCurrentTags();
        };
    }
 
    public function saveKeys(){
        if(is_array($this->keys_array)){
            $oldKeys = ArrayHelper::map($this->keys, 'name', 'id');
            foreach ($this->keys_array as $oneNewKey){
                if(isset($oldKeys[$oneNewKey])){
                    unset($oldKeys[$oneNewKey]);
                }else{
                    $this->createNewKey($oneNewKey);
                }
            }
            ArticlesKeys::deleteAll(['and', ['article_id'=>$this->id], ['keys_id'=>$oldKeys]]);
        }
        else{
            $this->clearCurrentKeys();
        };
    }
 
 
    public function beforeSave($insert)
    {
        if($file = UploadedFile::getInstance($this, 'file')){
            $dir = 'images/'. date("Y-m-d") . '/';
            if(!is_dir($dir)){
                mkdir($dir);
            }
 
            $file_name = uniqid() . '_' . $file->baseName . '.' . $file->extension;
            $this->image = $dir . $file_name;
            $file->saveAs($this->image);
        }
 
        return parent::beforeSave($insert);
    }
 
 
    public function beforeDelete()
    {
        if(parent::beforeDelete()){
//            $this->deleteImage();
            $this->clearCurrentTags();
            $this->clearCurrentKeys();
            return true;
        }else{
            return false;
        }
    }
 
 
 
 
    public function afterFind(){
//        $this->tags_array = $this->tags;
        $this->tags_array = ArrayHelper::map($this->tags,'name', 'name');
        $this->keys_array = ArrayHelper::map($this->keys,'name', 'name');
    }
 
 
    /*
    *сохранение в бд статья тэг после сохранения в артайкл
    */
    public function afterSave($insert, $changedAttributes)
    {
        parent::afterSave($insert, $changedAttributes);
        $this->saveTags();
        $this->saveKeys();
    }
 
    private function createNewTag($newTag){
        if(!$tag = Tag::find()->andWhere(['name'=>$newTag])->one()){
            $tag = new Tag;
            $tag->name = $newTag;
            if(!$tag->save()){
                $tag = null;
            }
        }
 
        if($tag instanceof Tag){
            $articleTag = new ArticleTag();
            $articleTag->article_id = $this->id;
            $articleTag->tag_id = $tag->id;
            if($articleTag->save())
                return $articleTag->article_id;
        }
        return false;
    }
 
    private function createNewKey($newKey){
        if(!$key = Keyswords::find()->andWhere(['name'=>$newKey])->one()){
            $key = new Keyswords;
            $key->name = $newKey;
            if(!$key->save()){
                $key = null;
            }
        }
 
        if($key instanceof Keyswords){
            $articleKey = new ArticlesKeys();
            $articleKey->article_id = $this->id;
            $articleKey->keys_id = $key->id;
            if($articleKey->save())
                return $articleKey->article_id;
        }
        return false;
    }
 
    public static function getArticleLimitDesc(){
        return Article::find()->with('category')->limit(3)->orderBy(['id' => SORT_DESC])->all();
    }
 
    public static function getArticleDesc(){
        return Article::find()->with('category')->orderBy(['id' => SORT_DESC]);
    }
 
//    public function getImage(){
//        return ($this->image) ? 'images/' . $this->image : 'no-image.png';
//    }
 
 
    public function getSelectedTags(){
        $selectedTags = $this->getTags()->select('id')->asArray()->all();
        return ArrayHelper::getColumn($selectedTags, 'id');
    }
 
 
    public function getTagsAsString(){
        $arr = ArrayHelper::map($this->getTags()->all(), 'id', 'name');
        return implode(',', $arr);
    }
 
 
    public function getCategory(){
        return $this->hasOne(Category::class, ['id' => 'category_id']);
    }
 
 
    public function getTags(){
        return $this->hasMany(Tag::class, ['id' => 'tag_id'])
            ->viaTable('article_tag', ['article_id' => 'id']);
    }
 
    public function getKeys(){
        return $this->hasMany(Keyswords::class, ['id' => 'keys_id'])
            ->viaTable('articles_keys', ['article_id' => 'id']);
    }
}
ArticleController

Код: Выделить всё

<?php
 
namespace app\modules\admin\controllers;
 
use app\models\Article;
use app\models\ArticleSearch;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
 
/**
 * ArticleController implements the CRUD actions for Article model.
 */
class ArticleController extends AppAdminController
{
    /**
     * @inheritDoc
     */
    public function behaviors()
    {
        return array_merge(
            parent::behaviors(),
            [
                'verbs' => [
                    'class' => VerbFilter::class,
                    'actions' => [
                        'delete' => ['POST'],
                    ],
                ],
            ]
        );
    }
 
    /**
     * Lists all Article models.
     * @return mixed
     */
    public function actionIndex()
    {
        $searchModel = new ArticleSearch();
        $dataProvider = $searchModel->search($this->request->queryParams);
 
        return $this->render('index', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        ]);
    }
 
    /**
     * Displays a single Article model.
     * @param int $id ID
     * @return mixed
     * @throws NotFoundHttpException if the model cannot be found
     */
    public function actionView($id)
    {
        return $this->render('view', [
            'model' => $this->findModel($id),
        ]);
    }
 
    /**
     * Creates a new Article model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionCreate()
    {
        $model = new Article();
 
        if ($this->request->isPost) {
            if ($model->load($this->request->post()) && $model->save()) {
                return $this->redirect(['view', 'id' => $model->id]);
            }
        }
        else {
            $model->loadDefaultValues();
        }
 
        return $this->render('create', [
            'model' => $model,
        ]);
    }
 
    /**
     * Updates an existing Article model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param int $id ID
     * @return mixed
     * @throws NotFoundHttpException if the model cannot be found
     */
    public function actionUpdate($id)
    {
        $model = $this->findModel($id);
 
        if ($this->request->isPost && $model->load($this->request->post()) && $model->save()) {
            return $this->redirect(['view', 'id' => $model->id]);
        }
 
        return $this->render('update', [
            'model' => $model,
        ]);
    }
 
    /**
     * Deletes an existing Article model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * @param int $id ID
     * @return mixed
     * @throws NotFoundHttpException if the model cannot be found
     */
    public function actionDelete($id)
    {
        $this->findModel($id)->delete();
 
        return $this->redirect(['index']);
    }
 
    /**
     * Finds the Article model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param int $id ID
     * @return Article the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
        if (($model = Article::findOne($id)) !== null) {
            return $model;
        }
 
        throw new NotFoundHttpException('The requested page does not exist.');
    }
}
_form

Код: Выделить всё

<?php
 
use yii\helpers\Html;
use yii\widgets\ActiveForm;
use kartik\select2\Select2;
use app\models\Tag;
use app\models\Keyswords;
use yii\helpers\ArrayHelper;
use mihaildev\ckeditor\CKEditor;
use mihaildev\elfinder\ElFinder;
use kartik\file\FileInput;
 
mihaildev\elfinder\Assets::noConflict($this);
 
/* @var $this yii\web\View */
/* @var $model app\models\Article */
/* @var $form yii\widgets\ActiveForm */
?>
 
<div class="article-form">
 
    <?php $form = ActiveForm::begin(); ?>
 
    <?= $form->field($model, 'title')->textInput(['maxlength' => true]) ?>
    <div class="col-md-2">
 
<!--        --><?//= $form->field($model,'category_id')->textInput() ?>
        <div class="form-group field-article-category_id has-success">
            <label for="article-category_id" class="control-label">Выбор категории</label>
            <select name="Article[category_id]" id="article-category_id" class="form-control">
                <?= \app\components\MenuWidget::widget([
                    'tpl' => 'articleselect',
                    'model' => $model,
                    'cache_time' => 0
                ])?>
            </select>
        </div>
    </div>
    <div class="col-md-5">
        <?= $form->field($model, 'keys_array')->
        widget(Select2::class,([
            'language' => 'ru',
            'data' => ArrayHelper::map(Keyswords::find()->all(), 'name', 'name'),
            'maintainOrder' => true,
            'options' => ['placeholder' => 'Введите ключевые слова ...', 'multiple' => true],
            'pluginOptions' => [
                'allowClear' => true,
                'tags' => true,
                'maximumInputLength' => 10
            ]
        ])) ?>
    </div>
 
    <div class="col-md-5">
        <?= $form->field($model, 'tags_array')->
        widget(Select2::class,([
            'language' => 'ru',
            'data' => ArrayHelper::map(Tag::find()->all(), 'name', 'name'),
            'maintainOrder' => true,
            'options' => ['placeholder' => 'Введите теги ...', 'multiple' => true],
            'pluginOptions' => [
                'allowClear' => true,
                'tags' => true,
                'maximumInputLength' => 10
            ]
        ])) ?>
    </div>
 
    <?echo $form->field($model, 'file')->widget(FileInput::class, [
        'options' => ['accept' => 'images/*'],
        'pluginOptions' => [
            'showCaption' => false,
            'showUpload' => false,
        ]
    ]);?>
 
    <?= $form->field($model, 'metaDescription')->textarea(['rows' => 6]) ?>
    <?= $form->field($model, 'description')->textarea(['rows' => 6]) ?>
 
<!--    --><?//= $form->field($model, 'content')->textarea(['rows' => 6]) ?>
 
    <?echo $form->field($model, 'content')->widget(CKEditor::class, [
        'editorOptions' => ElFinder::ckeditorOptions('elfinder',[/* Some CKEditor Options */]),
    ]);?>
 
    <div class="form-group">
        <?= Html::submitButton('Сохранить', ['class' => 'btn btn-success']) ?>
    </div>
 
    <?php ActiveForm::end(); ?>
 
</div>

$_FILES

Код: Выделить всё

[
    'name' => [
        'file' => 'IMG_20200707_120303.jpg'
    ]
    'type' => [
        'file' => 'image/jpeg'
    ]
    'tmp_name' => [
        'file' => 'C:\\OpenServer\\userdata\\php_upload\\php998E.tmp'
    ]
    'error' => [
        'file' => 0
    ]
    'size' => [
        'file' => 3462670
    ]
]

$_POST

Код: Выделить всё

[
    'title' => 'qeqeqeqe'
    'category_id' => '2'
    'keys_array' => [
        0 => '222'
    ]
    'tags_array' => [
        0 => 'fdfd'
    ]
    'file' => ' '
    'metaDescription' => 'qeqeqeqe'
    'description' => 'qeqeqeqe'
    'content' => '<p>qeqeqeqe</p>
'
]
die1990
Сообщения: 15
Зарегистрирован: 2021.12.21, 20:18

Re: почему при обновлении данные сохраняются а при добавлении нет yii2?

Сообщение die1990 »

Разобрался, дело было с добавлением фото, свойство $file было пустым, ведь в него ничего не приходило...в видосе ошиблись видимо, или я что то не понимаю.

Код: Выделить всё

    public function beforeSave($insert)
    {
        //Yii::getAlias('@web').
        if($this->file = UploadedFile::getInstance($this, 'file')){
            $dir = 'images/'. date("Y-m-d") . '/';
            if(file_exists($dir.$this->image)){
                unlink($dir.$this->image);
            }
            if(!is_dir($dir)){
                mkdir($dir);
            }

            $this->image = uniqid() . '_' . $this->file->baseName . '.' . $this->file->extension;
            $this->file->saveAs($dir.$this->image);
        }

        return parent::beforeSave($insert);
    }
Заменил $file на $this->file и все заработало. Еще там была небольшая проблема с добавлением ключей. В модели Article было не нужное поле keywords из за этого так же не сохранялось ничего
Ответить