Не загружаются картинки.

Общие вопросы по использованию второй версии фреймворка. Если не знаете как что-то сделать и это про Yii 2, вам сюда.
Artikk
Сообщения: 742
Зарегистрирован: 2017.02.10, 09:12

Не загружаются картинки.

Сообщение Artikk »

https://github.com/CostaRico/yii2-images делаю все ка тут, но не загружаются.
Контроллер:

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

<?php

namespace app\modules\admin\controllers;

use Yii;
use app\modules\admin\models\Galleryz;
use yii\data\ActiveDataProvider;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;

/**
 * GalleryzController implements the CRUD actions for Galleryz model.
 */
class GalleryzController extends Controller
{
    /**
     * @inheritdoc
     */
    public function behaviors()
    {
        return [
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['POST'],
                ],
            ],
        ];
    }

    /**
     * Lists all Galleryz models.
     * @return mixed
     */
    public function actionIndex()
    {
        $dataProvider = new ActiveDataProvider([
            'query' => Galleryz::find(),
        ]);

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

    /**
     * Displays a single Galleryz model.
     * @param integer $id
     * @return mixed
     */
    public function actionView($id)
    {
        return $this->render('view', [
            'model' => $this->findModel($id),
        ]);
    }

    /**
     * Creates a new Galleryz model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionCreate()
    {
        $model = new Galleryz();

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            return $this->redirect(['view', 'id' => $model->id]);
        } else {
            return $this->render('create', [
                'model' => $model,
            ]);
        }
    }

    /**
     * Updates an existing Galleryz model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param integer $id
     * @return mixed
     */
    public function actionUpdate($id)
    {
        $model = $this->findModel($id);

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            return $this->redirect(['view', 'id' => $model->id]);
        } else {
            return $this->render('update', [
                'model' => $model,
            ]);
        }
    }

    /**
     * Deletes an existing Galleryz model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * @param integer $id
     * @return mixed
     */
    public function actionDelete($id)
    {
        $this->findModel($id)->delete();

        return $this->redirect(['index']);
    }

    /**
     * Finds the Galleryz model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param integer $id
     * @return Galleryz the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
        if (($model = Galleryz::findOne($id)) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }
}

модель:

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

<?php

namespace app\modules\admin\models;

use Yii;

/**
 * This is the model class for table "gallery".
 *
 * @property integer $id
 * @property string $name
 * @property string $foto
 */
class Galleryz extends \yii\db\ActiveRecord
{
    public $image;

    public function behaviors()
    {
        return [
            'image' => [
                'class' => 'rico\yii2images\behaviors\ImageBehave',
            ]
        ];
    }

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

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['name', 'foto'], 'required'],
            [['name', 'foto'], 'string', 'max' => 255],
            [['image'], 'file', 'extensions' => 'png, jpg'],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'name' => 'Name',
            'image' => 'Фото',
        ];
    }

    public function upload(){
        if ($this->validate()) {
            $path = 'upload/store/' . $this->image->baseName . '.' . $this->image->extension;
            $this->image->saveAs($path);
            $this->attachImage($path);
            @unlink($path);//удаляем старую картинку
            return true;
        } else {
            return false;
        }
    }
}

Вид формы:

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

<?php

use yii\helpers\Html;
use yii\widgets\ActiveForm;

/* @var $this yii\web\View */
/* @var $model app\modules\admin\models\Gallery */
/* @var $form yii\widgets\ActiveForm */
?>

<div class="gallery-form">

    <?php $form = ActiveForm::begin(['options' => ['enctype' => 'multipart/form-data']]); ?>

    <?= $form->field($model, 'name')->textInput(['maxlength' => true]) ?>

    <?= $form->field($model, 'image')->fileInput() ?>

    <div class="form-group">
        <?= Html::submitButton($model->isNewRecord ? 'Create' : 'Update', ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>
    </div>

    <?php ActiveForm::end(); ?>

</div>

Вид загрузки самой:

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

<?php

use yii\helpers\Html;


/* @var $this yii\web\View */
/* @var $model app\modules\admin\models\Gallery */

$this->title = 'Добавить картинку';
$this->params['breadcrumbs'][] = ['label' => 'Galleries', 'url' => ['index']];
$this->params['breadcrumbs'][] = $this->title;
?>
<div class="main">
    <div class="container">
        <div class="row">
            <div class="gallery-create">

                <h1><?= Html::encode($this->title) ?></h1>

                <?= $this->render('_form', [
                    'model' => $model,
                ]) ?>

            </div>
        </div>
    </div>
</div>


Последний раз редактировалось Artikk 2017.03.23, 09:07, всего редактировалось 1 раз.
Artikk
Сообщения: 742
Зарегистрирован: 2017.02.10, 09:12

Re: Не загружаются картинки.

Сообщение Artikk »

вроде все сделалл так, как там, но не работает.
Artikk
Сообщения: 742
Зарегистрирован: 2017.02.10, 09:12

Re: Не загружаются картинки.

Сообщение Artikk »

Мне кажется, что ошибка тут:

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

public function rules()
    {
        return [
            [['name', 'foto'], 'required'],
            [['name', 'foto'], 'string', 'max' => 255],
            [['image'], 'file', 'extensions' => 'png, jpg'],
        ];
    }

или нет?
Artikk
Сообщения: 742
Зарегистрирован: 2017.02.10, 09:12

Re: Не загружаются картинки.

Сообщение Artikk »

уже разобрался
Sandro
Сообщения: 10
Зарегистрирован: 2017.11.09, 15:03

Re: Не загружаются картинки.

Сообщение Sandro »

Здравствуйте!
У меня аналогичная проблема с установкой https://github.com/CostaRico/yii2-images

Что не так сделано?

Setup module common/config/main

main.php

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

<?php
use \kartik\datecontrol\Module;
return [
    'vendorPath' => dirname(dirname(__DIR__)) . '/vendor',
    'modules'=>[

 'yii2images' => [
            'class' => 'rico\yii2images\Module',
            //be sure, that permissions ok
            //if you cant avoid permission errors you have to create "images" folder in web root manually and set 777 permissions
            'imagesStorePath' => 'images/store', //path to origin images
            'imagesCachePath' => 'images/cache', //path to resized copies
            'graphicsLibrary' => 'GD', //but really its better to use 'Imagick'
            'placeHolderPath' => '@webroot/images/placeHolder.png', // if you want to get placeholder when image not exists, string will be processed by Yii::getAlias
       ],

        'datecontrol' =>  [
            'class' => 'kartik\datecontrol\Module',

          // format settings for displaying each date attribute (ICU format example)
            'displaySettings' => [
                Module::FORMAT_DATE => 'yyyy-M-dd',
                Module::FORMAT_TIME => 'php: H:i',
                Module::FORMAT_DATETIME => 'php:d M Y H:i',
            ],

          // format settings for saving each date attribute (PHP format example)
            'saveSettings' => [
                Module::FORMAT_DATE => 'php:U',
                Module::FORMAT_TIME => 'php:U',
                Module::FORMAT_DATETIME => 'php:U',
            ],

          // set your display timezone
            'displayTimezone' => 'europe/moscow',

          // set your timezone for date saved to db
            'saveTimezone' => 'UTC',

          // automatically use kartik\widgets for each of the above formats
            'autoWidget' => true,
        ] 
    ], 

    'components' => [
        'cache' => [
            'class' => 'yii\caching\FileCache',
        ],
        'settings' => [
            'class' => 'wokster\settings\components\Settings',
        ],
        'image' => [
            'class' => 'yii\image\ImageDriver',
            'driver' => 'GD',  //GD or Imagick
        ],
        'i18n' => [
            'translations' => [
                'file-input' => [
                    'class' => 'yii\i18n\PhpMessageSource',
                    'basePath' => 'dosamigos\fileinput\src\messages',
                ],
            ],
        ],
    ],
];
Arcticle.php

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

<?php

namespace wokster\article\models;

use wokster\behaviors\ImageUploadBehavior;
use wokster\behaviors\StatusBehavior;
use wokster\tags\TagsBehavior;
use Yii;
use yii\behaviors\TimestampBehavior;
use yii\helpers\StringHelper;
use yii\helpers\Url;



/**
 * This is the model class for table "article".
 *
 * @property integer $id
 * @property string $title
 * @property string $url
 * @property string $text
 * @property integer $status_id
 * @property string $image
 * @property integer $date_create
 * @property integer $type_id
 * @property integer $date_start
 * @property integer $date_finish

 */
class Article extends \yii\db\ActiveRecord
{
    public $file;
    public $image;



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

    /**
    * @inheritdoc
    */
    public function behaviors()
    {
        return [
            'status' => [
              'class' => StatusBehavior::className(),
              'status_value' => $this->status_id,
               'statusList' => Yii::$app->modules['article']->status_list,
            ],
           

            'image' => [
               /* 'class' => ImageUploadBehavior::className(),*/
               'class' => 'rico\yii2images\behaviors\ImageBehave',
                'attribute' => 'image',
                'random_name' => 'true',
                'image_path' => Yii::$app->modules['article']->imagePath,
                'image_url' => Yii::$app->modules['article']->imageUrl,
                'size_for_resize' => [
                                [640,480,true],
                                [640,null,false],
                                [50,50,true]
                                ]
            ],
            'timestamp' => [
                'class' => TimestampBehavior::className(),
                'createdAtAttribute' => 'date_create',
                'updatedAtAttribute' => false,
            ],
            'seo' => [
                'class' => \wokster\seomodule\SeoBehavior::className(),
            ],
            'tags' => [
                'class' => TagsBehavior::className(),
            ],
        ];
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['title', 'url'], 'required'],
            [['date_start', 'date_finish'], 'required', 'when' => function($model) {
                return $model->type_id == \wokster\article\Article::TYPE_SALE;
            }],
            [['text'], 'string'],
            [['status_id', 'date_create', 'type_id', 'date_start', 'date_finish'], 'integer'],
            [['title', 'image'], 'string', 'max' => 255],
            [['url'], 'string', 'max' => 100],
            [['url'], 'unique'],
           

            [['url'], 'match', 'pattern' => '/^[a-z0-9_-]+$/', 'message' => 'Недопустимые символы в url'],
            [['status_id'], 'default','value'=>0],
            ['file'],
            [['image'], 'file', 'extensions' => 'jpg'],
        ];
    }

        public function upload(){
        if($this->validate()){
            $path = 'images/store' . $this->image->baseName . '.' . $this->image->extension;
            $this->image->saveAs($path);
            return true;
        } else {
            return false;
        }
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'title' => 'заглавие',
            'url' => 'ЧПУ',
            'text' => 'контент',
            'status_id' => 'статус',
            'image' => 'картинка',
            'date_create' => 'дата публикации',
            'type_id' => 'тип',
            'Status' => 'статус',
      
            'date_start' => 'дата начала',
            'date_finish' => 'дата окончания'
        ];
    }

    /**
     * @return mixed
     */
    public static function getTypeList(){
        return Yii::$app->modules['article']->type_list;
    }

    /**
     * @return string
     */
    public function getTypeName(){
        $list = self::getTypeList();
        return (isset($list[$this->type_id]))?$list[$this->type_id]:'';
    }

    /**
     * @return string
     */
    public function getShortText(){
        return StringHelper::truncateWords(strip_tags($this->text),50);
    }
}
attach behaviour
Arcticle.php

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

<?php

namespace wokster\article\models;

use wokster\behaviors\ImageUploadBehavior;
use wokster\behaviors\StatusBehavior;
use wokster\tags\TagsBehavior;
use Yii;
use yii\behaviors\TimestampBehavior;
use yii\helpers\StringHelper;
use yii\helpers\Url;



/**
 * This is the model class for table "article".
 *
 * @property integer $id
 * @property string $title
 * @property string $url
 * @property string $text
 * @property integer $status_id
 * @property string $image
 * @property integer $date_create
 * @property integer $type_id
 * @property integer $date_start
 * @property integer $date_finish

 */
class Article extends \yii\db\ActiveRecord
{
    public $file;
    public $image;



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

    /**
    * @inheritdoc
    */
    public function behaviors()
    {
        return [
            'status' => [
              'class' => StatusBehavior::className(),
              'status_value' => $this->status_id,
               'statusList' => Yii::$app->modules['article']->status_list,
            ],
           

            'image' => [
               /* 'class' => ImageUploadBehavior::className(),*/
               'class' => 'rico\yii2images\behaviors\ImageBehave',
                'attribute' => 'image',
                'random_name' => 'true',
                'image_path' => Yii::$app->modules['article']->imagePath,
                'image_url' => Yii::$app->modules['article']->imageUrl,
                'size_for_resize' => [
                                [640,480,true],
                                [640,null,false],
                                [50,50,true]
                                ]
            ],
            'timestamp' => [
                'class' => TimestampBehavior::className(),
                'createdAtAttribute' => 'date_create',
                'updatedAtAttribute' => false,
            ],
            'seo' => [
                'class' => \wokster\seomodule\SeoBehavior::className(),
            ],
            'tags' => [
                'class' => TagsBehavior::className(),
            ],
        ];
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['title', 'url'], 'required'],
            [['date_start', 'date_finish'], 'required', 'when' => function($model) {
                return $model->type_id == \wokster\article\Article::TYPE_SALE;
            }],
            [['text'], 'string'],
            [['status_id', 'date_create', 'type_id', 'date_start', 'date_finish'], 'integer'],
            [['title', 'image'], 'string', 'max' => 255],
            [['url'], 'string', 'max' => 100],
            [['url'], 'unique'],
           

            [['url'], 'match', 'pattern' => '/^[a-z0-9_-]+$/', 'message' => 'Недопустимые символы в url'],
            [['status_id'], 'default','value'=>0],
            ['file'],
            [['image'], 'file', 'extensions' => 'jpg'],
        ];
    }

        public function upload(){
        if($this->validate()){
            $path = 'images/store' . $this->image->baseName . '.' . $this->image->extension;
            $this->image->saveAs($path);
            return true;
        } else {
            return false;
        }
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'title' => 'заглавие',
            'url' => 'ЧПУ',
            'text' => 'контент',
            'status_id' => 'статус',
            'image' => 'картинка',
            'date_create' => 'дата публикации',
            'type_id' => 'тип',
            'Status' => 'статус',
      
            'date_start' => 'дата начала',
            'date_finish' => 'дата окончания'
        ];
    }

    /**
     * @return mixed
     */
    public static function getTypeList(){
        return Yii::$app->modules['article']->type_list;
    }

    /**
     * @return string
     */
    public function getTypeName(){
        $list = self::getTypeList();
        return (isset($list[$this->type_id]))?$list[$this->type_id]:'';
    }

    /**
     * @return string
     */
    public function getShortText(){
        return StringHelper::truncateWords(strip_tags($this->text),50);
    }
}
ArcticleController

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

<?php

namespace wokster\article\controllers;

use yii;
use wokster\article\models\Article;
use wokster\article\models\ArticleSearch;
use yii\web\MethodNotAllowedHttpException;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;

/**
 * ArticleController implements the CRUD actions for Article model.
 */
class ArticleController extends yii\web\Controller
{
    public function behaviors()
    {
        return [
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['post'],
                ],
            ],
        ];
    }


    public function actions()
    {
        return [
            'images-get' => [
                'class' => 'vova07\imperavi\actions\GetAction',
                'url' => \Yii::$app->controller->module->allRedactorImageUrl, // Directory URL address, where files are stored.
                'path' => \Yii::$app->controller->module->redactor_upload_path_alias, // Or absolute path to directory where files are stored.
                'type' => \vova07\imperavi\actions\GetAction::TYPE_IMAGES,
            ],
            'image-upload' => [
                'class' => 'vova07\imperavi\actions\UploadAction',
                'url' => \Yii::$app->controller->module->redactorImageUrl, // Directory URL address, where files are stored.
                'path' => \Yii::$app->controller->module->redactorPath, // Or absolute path to directory where files are stored.
            ],
        ];
    }

    /**
     * Lists all Article models.
     * @return mixed
     */
    public function actionIndex()
    {
        $searchModel = new ArticleSearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);

        return $this->render('index', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        ]);
    }

    /**
     * Displays a single Article model.
     * @param integer $id
     * @return mixed
     */
    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($type=null)
    {
        $model = new Article();
        if(is_numeric($type))
            $model->type_id = $type;

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            if(Yii::$app->request->post('toview',false)){
                return $this->redirect(['view', 'id' => $model->id]);
            }else{
                return $this->redirect(['update', 'id' => $model->id]);
            }

        } else {
            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 integer $id
     * @return mixed
     */
    public function actionUpdate($id)
    {
        $model = $this->findModel($id);

       /* if ($model->load(Yii::$app->request->post()) && $model->save()) {
            return $this->redirect(['update', 'id' => $model->id]);
        } else {
            return $this->render('update', [
                'model' => $model,
            ]);
        }*/

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            $model->image = UploadedFile::getInstance($model, 'image');
            if ($model->image){
                $model->upload();
            }

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

    /**
     * Deletes an existing Article model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * @param integer $id
     * @return mixed
     */
    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 integer $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;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }
}
form.php

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

<?php

use yii\helpers\Html;
use kartik\form\ActiveForm;
use \dosamigos\fileinput\FileInput;
use yii\helpers\Url;

/* @var $this yii\web\View */
/* @var $model wokster\article\models\Article */
/* @var $form yii\widgets\ActiveForm */
/* @var $model app\modules\admin\models\Gallery */

if($model->hasErrors()):
  \wokster\ltewidgets\BoxWidget::begin([
      'solid'=>true,
      'color'=>'danger',
      'title'=>'Ошибки валидации',
      'close'=> true,
  ]);
  $error_data = $model->firstErrors;
  echo \yii\widgets\DetailView::widget([
      'model'=>$error_data,
      'attributes'=>array_keys($error_data)
  ]);
  \wokster\ltewidgets\BoxWidget::end();
endif;
?>

<div class="-article-form">

    <?php $form = ActiveForm::begin(['options' => ['enctype' => 'multipart/form-data']]); ?>

    <?= $form->field($model, 'name')->textInput(['maxlength' => true]) ?>

    <?= $form->field($model, 'image')->fileInput() ?>

    <div class="form-group">
        <?= Html::submitButton($model->isNewRecord ? 'Create' : 'Update', ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>
    </div>

    <?php ActiveForm::end(); ?>

</div>


<div class="article-form">
    <?php $form = ActiveForm::begin([
      'options' => ['enctype'=>'multipart/form-data'],
      'enableClientValidation' => false
    ]); ?>

          <?= $form->field($model, 'title', ['addon' => ['prepend' => ['content' => '<i class="fa fa-pencil"></i>']],'options'=>['class'=>'col-xs-12 col-md-6']])->textInput(['maxlength' => true]) ?>

	        <?=  $form->field($model, 'url', ['addon' => ['prepend' => ['content' => '<i class="fa fa-globe"></i>']],'options'=>['class'=>'col-xs-12 col-md-6']])->widget(\wokster\behaviors\TranslitWidget::className())
 ?>

	        <?=  $form->field($model, 'text',['options'=>['class'=>'col-xs-12']])->widget(\vova07\imperavi\Widget::className(),[
              'settings' => [
                  'lang' => 'ru',
                  'minHeight' => 200,
                  'pastePlainText' => true,
                  'imageUpload' => \yii\helpers\Url::toRoute(['/article/article/image-upload']),
                  'imageManagerJson' => \yii\helpers\Url::toRoute(['/article/article/images-get']),
                   /*'imageUpload' => \yii\helpers\Url::to (['/site/save-redactor-img']),*/
                  'replaceDivs' => false,
                  'formattingAdd' => [
                      [
                          'tag' => 'p',
                          'title' => 'text-success',
                          'class' => 'text-success'
                      ],
                      [
                          'tag' => 'p',
                          'title' => 'text-danger',
                          'class' => 'text-danger'
                      ],
                  ],
                  'plugins' => [
                      'fullscreen',
                      'table',
                      'imagemanager',
                      'fontcolor',
                      'fontsize',
                      'video'
                  ]
              ]
          ])

 ?>



  <div class="row">
  <div class="col-xs-8">
    <?=  $form->field($model, 'status_id',['options'=>['class'=>'col-xs-12']])->dropDownList(Yii::$app->modules['article']->status_list)
    ?>

    <?= $form->field($model, 'type_id', ['addon' => ['prepend' => ['content' => '<i class="fa fa-pencil"></i>']],'options'=>['class'=>'col-xs-12']])->dropDownList(Yii::$app->modules['article']->type_list) ?>

    <div class="<?= ($model->type_id == \wokster\article\Article::TYPE_PAGE)?' hidden':''?>" id="start-date-div">
      <?= $form->field($model, 'date_start', ['options'=>['class'=>'col-xs-12']])->widget(\kartik\datecontrol\DateControl::className(),[]) ?>
    </div>

    <div class="<?= ($model->type_id == \wokster\article\Article::TYPE_SALE)?'':' hidden'?>" id="sale-date-div">
      <?= $form->field($model, 'date_finish', ['options'=>['class'=>'col-xs-12']])->widget(\kartik\datecontrol\DateControl::className(),[]) ?>
    </div>

    <?= $form->field($model, 'new_tags', ['addon' => ['prepend' => ['content' => '<i class="fa fa-pencil"></i>']],'options'=>['class'=>'col-xs-12']])->widget(\wokster\tags\TagsInputWidget::className()) ?>
  </div>
  <div class="col-xs-4">
    <?= $form->field($model, 'file', ['options'=>['class'=>'col-xs-12']])->label(false)->widget(FileInput::className(),[
        'attribute' => 'image', // image is the attribute
      // using STYLE_IMAGE allows me to display an image. Cool to display previously
      // uploaded images
        'thumbnail' => '<img src="'.$model->getImage().'" />',
        'style' => FileInput::STYLE_IMAGE
    ]);?>
  </div>

  <?php $form = ActiveForm::begin(['options' => ['enctype' => 'multipart/form-data']]); ?>
<?=$form->field($model, 'image')->fileInput() ?>
  </div>
  <?= \wokster\seomodule\SeoFormWidget::widget(['model'=>$model,'form'=>$form]);?>
  <div class="row">
    <div class="col-xs-12 col-md-12">
      <div class="form-group">
        <?= Html::submitButton('Сохранить', ['class' =>'btn btn-success']) ?>
      </div>
    </div>
  </div>
  <?php ActiveForm::end(); ?>
</div>
<?php $this->registerJs("
  $('#article-type_id').on('change',function(){
  var type = $(this).val();
    if(type == ".\wokster\article\Article::TYPE_SALE."){
      $('#sale-date-div').removeClass('hidden');
      $('#start-date-div').removeClass('hidden');
    }else if(type == ".\wokster\article\Article::TYPE_NEWS."){
      $('#sale-date-div').addClass('hidden');
      $('#start-date-div').removeClass('hidden');
    }else{
      $('#sale-date-div').addClass('hidden');
      $('#start-date-div').addClass('hidden');
    }
  });
");
В итоге у меня сейчас ошибка: Изображение
Изображение
Изображение
Изображение
Аватара пользователя
Dominus
Сообщения: 892
Зарегистрирован: 2013.03.14, 21:27
Откуда: Россия, Иваново
Контактная информация:

Re: Не загружаются картинки.

Сообщение Dominus »

Ну ошибка говорит о том что в ImageBehave нет параметра "attribute" который вы пытаетесь установить.

Попробуйте подключить расширение так, как указано в документации к расширению: https://github.com/CostaRico/yii2-image ... /README.md
Не спорь с дураком, иначе окружающие не правильно поймут кто из вас дурак!
Никита096
Сообщения: 28
Зарегистрирован: 2017.02.01, 17:23

Re: Не загружаются картинки.

Сообщение Никита096 »

Забейте вы на yii2-images, есть хорошее гибкое расширение от dream-team: yii-dream-team/yii2-upload-behavior
Sandro
Сообщения: 10
Зарегистрирован: 2017.11.09, 15:03

Re: Не загружаются картинки.

Сообщение Sandro »

Ну ошибка говорит о том что в ImageBehave нет параметра "attribute" который вы пытаетесь установить.
Да, так и есть. Ещё до установки yii2-images было установлено другое приложение (которое не заработало) И эти параметры в модели остались.
К нему, cогласно документации CostaRico/yii2-images была добавлена строчка в поведение Arcticle.php

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

'image' => [
                'class' => 'rico\yii2images\behaviors\ImageBehave',
Но! Если этот кусок кода убрать

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

'attribute' => 'image',
                'random_name' => 'true',
                'image_path' => Yii::$app->modules['article']->imagePath,
                'image_url' => Yii::$app->modules['article']->imageUrl,
                'size_for_resize' => [
                                [640,480,true],
                                [640,null,false],
                                [50,50,true]
                                ]
то появляется следующая ошибка:Изображение
Изображение
Изображение
Изображение
Аватара пользователя
Dominus
Сообщения: 892
Зарегистрирован: 2013.03.14, 21:27
Откуда: Россия, Иваново
Контактная информация:

Re: Не загружаются картинки.

Сообщение Dominus »

Согласно документации, поведение подключается так:

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

    public function behaviors()
    {
        return [
            'image' => [
                'class' => 'rico\yii2images\behaviors\ImageBehave',
                //'createAliasMethod' => true,
                // Другие параметры поведение не принимает
            ],
            //...
        ];
    }
Настраивается модуль в конфиге приложения:

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

    'modules' => [
        'yii2images' => [
            'class' => 'rico\yii2images\Module',
            // Настройки модуля
            //...
        ],       
    ],
Ну и миграцию надо применить

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

php yii migrate/up --migrationPath=@vendor/costa-rico/yii2-images/migrations
Не спорь с дураком, иначе окружающие не правильно поймут кто из вас дурак!
Аватара пользователя
Dominus
Сообщения: 892
Зарегистрирован: 2013.03.14, 21:27
Откуда: Россия, Иваново
Контактная информация:

Re: Не загружаются картинки.

Сообщение Dominus »

И да, этот модуль не занимается загрузкой изображений. Он делает привязку любой модели к уже загруженным изображениям с последующим выводом нужных размеров, и возможностью установки основного изображения.
Yii2-images is yii2 module that allows to attach images to any of your models, next you can get images in any sizes, also you can set main image of images set.
Не спорь с дураком, иначе окружающие не правильно поймут кто из вас дурак!
Sandro
Сообщения: 10
Зарегистрирован: 2017.11.09, 15:03

Re: Не загружаются картинки.

Сообщение Sandro »

Доброго времени суток!

Пробую установить yii-dream-team/yii2-upload-behavior

В документации Attach the behavior to your model class:

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

public function behaviors()
{
    return [
        [
            'class' => '\yiidreamteam\upload\FileUploadBehavior',
            'attribute' => 'fileUpload',
            'filePath' => '@webroot/uploads/[[pk]].[[extension]]',
            'fileUrl' => '/uploads/[[pk]].[[extension]]',
        ],
    ];
}
Куда именно добавить это нужно?
model Arcticle.php

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

<?php

namespace wokster\article\models;

use wokster\behaviors\ImageUploadBehavior;
use wokster\behaviors\StatusBehavior;
use wokster\tags\TagsBehavior;
use Yii;
use yii\behaviors\TimestampBehavior;
use yii\helpers\StringHelper;
use yii\helpers\Url;


/**
 * This is the model class for table "article".
 *
 * @property integer $id
 * @property string $title
 * @property string $url
 * @property string $text
 * @property integer $status_id
 * @property string $image
 * @property integer $date_create
 * @property integer $type_id
 * @property integer $date_start
 * @property integer $date_finish

 */
class Article extends \yii\db\ActiveRecord
{
    public $file;

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

    /**
    * @inheritdoc
    */
    public function behaviors()
    {
        return [
            'status' => [
              'class' => StatusBehavior::className(),
              'status_value' => $this->status_id,
               'statusList' => Yii::$app->modules['article']->status_list,
            ],
            'image' => [
                'class' => ImageUploadBehavior::className(),
                'attribute' => 'image',
                'random_name' => 'true',
                'image_path' => Yii::$app->modules['article']->imagePath,
                'image_url' => Yii::$app->modules['article']->imageUrl,
                'size_for_resize' => [
                                [640,480,true],
                                [640,null,false],
                                [50,50,true]
                                ]
            ],
            'timestamp' => [
                'class' => TimestampBehavior::className(),
                'createdAtAttribute' => 'date_create',
                'updatedAtAttribute' => false,
            ],
            'seo' => [
                'class' => \wokster\seomodule\SeoBehavior::className(),
            ],
            'tags' => [
                'class' => TagsBehavior::className(),
            ],
        ];
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['title', 'url'], 'required'],
            [['date_start', 'date_finish'], 'required', 'when' => function($model) {
                return $model->type_id == \wokster\article\Article::TYPE_SALE;
            }],
            [['text'], 'string'],
            [['status_id', 'date_create', 'type_id', 'date_start', 'date_finish'], 'integer'],
            [['title', 'image'], 'string', 'max' => 255],
            [['url'], 'string', 'max' => 100],
            [['url'], 'unique'],
           

            [['url'], 'match', 'pattern' => '/^[a-z0-9_-]+$/', 'message' => 'Недопустимые символы в url'],
            [['status_id'], 'default','value'=>0],
             ['fileUpload', 'file'],   
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'title' => 'заглавие',
            'url' => 'ЧПУ',
            'text' => 'контент',
            'status_id' => 'статус',
            'image' => 'картинка',
            'date_create' => 'дата публикации',
            'type_id' => 'тип',
            'Status' => 'статус',
      
            'date_start' => 'дата начала',
            'date_finish' => 'дата окончания'
        ];
    }

    /**
     * @return mixed
     */
    public static function getTypeList(){
        return Yii::$app->modules['article']->type_list;
    }

    /**
     * @return string
     */
    public function getTypeName(){
        $list = self::getTypeList();
        return (isset($list[$this->type_id]))?$list[$this->type_id]:'';
    }

    /**
     * @return string
     */
    public function getShortText(){
        return StringHelper::truncateWords(strip_tags($this->text),50);
    }
}
В rules добавлено:

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

['fileUpload', 'file'],
Далее в документации:
Setup proper form enctype:

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

$form = \yii\bootstrap\ActiveForm::begin([
    'enableClientValidation' => false,
    'options' => [
        'enctype' => 'multipart/form-data',
    ],
]);
form.php

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

<?php

use yii\helpers\Html;
use kartik\form\ActiveForm;
use \dosamigos\fileinput\FileInput;

/* @var $this yii\web\View */
/* @var $model wokster\article\models\Article */
/* @var $form yii\widgets\ActiveForm */

if($model->hasErrors()):
  \wokster\ltewidgets\BoxWidget::begin([
      'solid'=>true,
      'color'=>'danger',
      'title'=>'Ошибки валидации',
      'close'=> true,
  ]);
  $error_data = $model->firstErrors;
  echo \yii\widgets\DetailView::widget([
      'model'=>$error_data,
      'attributes'=>array_keys($error_data)
  ]);
  \wokster\ltewidgets\BoxWidget::end();
endif;
?>

<div class="article-form">
    <?php $form = ActiveForm::begin([
      'options' => ['enctype'=>'multipart/form-data'],
      'enableClientValidation' => false
    ]); ?>

          <?= $form->field($model, 'title', ['addon' => ['prepend' => ['content' => '<i class="fa fa-pencil"></i>']],'options'=>['class'=>'col-xs-12 col-md-6']])->textInput(['maxlength' => true]) ?>

          <?=  $form->field($model, 'url', ['addon' => ['prepend' => ['content' => '<i class="fa fa-globe"></i>']],'options'=>['class'=>'col-xs-12 col-md-6']])->widget(\wokster\behaviors\TranslitWidget::className())
 ?>

          <?=  $form->field($model, 'text',['options'=>['class'=>'col-xs-12']])->widget(\vova07\imperavi\Widget::className(),[
              'settings' => [
                  'lang' => 'ru',
                  'minHeight' => 200,
                  'pastePlainText' => true,
                  'imageUpload' => \yii\helpers\Url::toRoute(['/article/article/image-upload']),
                  'imageManagerJson' => \yii\helpers\Url::toRoute(['/article/article/images-get']),
                  'replaceDivs' => false,
                  'formattingAdd' => [
                      [
                          'tag' => 'p',
                          'title' => 'text-success',
                          'class' => 'text-success'
                      ],
                      [
                          'tag' => 'p',
                          'title' => 'text-danger',
                          'class' => 'text-danger'
                      ],
                  ],
                  'plugins' => [
                      'fullscreen',
                      'table',
                      'imagemanager',
                      'fontcolor',
                      'fontsize',
                      'video'
                  ]
              ]
          ])
 ?>
  <div class="row">
  <div class="col-xs-8">
    <?=  $form->field($model, 'status_id',['options'=>['class'=>'col-xs-12']])->dropDownList(Yii::$app->modules['article']->status_list)
    ?>

    <?= $form->field($model, 'type_id', ['addon' => ['prepend' => ['content' => '<i class="fa fa-pencil"></i>']],'options'=>['class'=>'col-xs-12']])->dropDownList(Yii::$app->modules['article']->type_list) ?>

    <div class="<?= ($model->type_id == \wokster\article\Article::TYPE_PAGE)?' hidden':''?>" id="start-date-div">
      <?= $form->field($model, 'date_start', ['options'=>['class'=>'col-xs-12']])->widget(\kartik\datecontrol\DateControl::className(),[]) ?>
    </div>

    <div class="<?= ($model->type_id == \wokster\article\Article::TYPE_SALE)?'':' hidden'?>" id="sale-date-div">
      <?= $form->field($model, 'date_finish', ['options'=>['class'=>'col-xs-12']])->widget(\kartik\datecontrol\DateControl::className(),[]) ?>
    </div>

    <?= $form->field($model, 'new_tags', ['addon' => ['prepend' => ['content' => '<i class="fa fa-pencil"></i>']],'options'=>['class'=>'col-xs-12']])->widget(\wokster\tags\TagsInputWidget::className()) ?>
  </div>
  <div class="col-xs-4">
    <?= $form->field($model, 'file', ['options'=>['class'=>'col-xs-12']])->label(false)->widget(FileInput::className(),[
        'attribute' => 'image', // image is the attribute
      // using STYLE_IMAGE allows me to display an image. Cool to display previously
      // uploaded images
        'thumbnail' => '<img src="'.$model->getImage().'" />',
        'style' => FileInput::STYLE_IMAGE
    ]);?>
  </div>
  </div>
  <?= \wokster\seomodule\SeoFormWidget::widget(['model'=>$model,'form'=>$form]);?>
  <div class="row">
    <div class="col-xs-12 col-md-12">
      <div class="form-group">
        <?= Html::submitButton('Сохранить', ['class' =>'btn btn-success']) ?>
      </div>
    </div>
  </div>
  <?php ActiveForm::end(); ?>
</div>
<?php $this->registerJs("
  $('#article-type_id').on('change',function(){
  var type = $(this).val();
    if(type == ".\wokster\article\Article::TYPE_SALE."){
      $('#sale-date-div').removeClass('hidden');
      $('#start-date-div').removeClass('hidden');
    }else if(type == ".\wokster\article\Article::TYPE_NEWS."){
      $('#sale-date-div').addClass('hidden');
      $('#start-date-div').removeClass('hidden');
    }else{
      $('#sale-date-div').addClass('hidden');
      $('#start-date-div').addClass('hidden');
    }
  });
");
Аватара пользователя
Dominus
Сообщения: 892
Зарегистрирован: 2013.03.14, 21:27
Откуда: Россия, Иваново
Контактная информация:

Re: Не загружаются картинки.

Сообщение Dominus »

Sandro писал(а): 2017.12.10, 17:29 Доброго времени суток!

Пробую установить yii-dream-team/yii2-upload-behavior
Model:

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

class Article extends \yii\db\ActiveRecord
{
    public $fileUpload;
    
    //...
    
    /**
     * @inheritdoc
     */
    public function behaviors()
    {
        return [            
            'upload1' => [
                'class' => '\yiidreamteam\upload\FileUploadBehavior',
                'attribute' => 'fileUpload',
                'filePath' => '@webroot/uploads/[[filename]].[[extension]]',
                'fileUrl' => '/uploads/[[filename]].[[extension]]',
            ],
            //...
        ];
    }
    
    public function rules()
    {
        return [
            //...
            ['fileUpload', 'file'],
        ];
    }
    
    //...    
}
Controller:

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

public function actionCreate()
{
    $model = new  Article();
        
    if ($model->load(Yii::$app->request->post()) && $model->validate()) {
        // $file - атрибут в модели для хранения пути до файла (поле в таблице БД)
        $model->file = $model->getUploadedFileUrl('fileUpload');
        if($model->save())
            return $this->redirect(['view', 'id' => $model->id]);
    } else {
        return $this->render('create', [
            'model' => $model,
        ]);
    }
}
Ну и представление:

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

<?php $form = ActiveForm::begin([
    'enableClientValidation' => false,
    'options' => [
        'enctype' => 'multipart/form-data',
    ],
]); ?>
<?= $form->field($model, 'fileUpload')->fileInput() ?>
//...
<?php ActiveForm::end(); ?>
Не спорь с дураком, иначе окружающие не правильно поймут кто из вас дурак!
Sandro
Сообщения: 10
Зарегистрирован: 2017.11.09, 15:03

Re: Не загружаются картинки.

Сообщение Sandro »

Добавил этот код в модель, контроллер и представление, но вылезла ошибка со свойством Getting unknown property: wokster\article\models\ArticleSearch::fileUpload
и DataProvaider

Ошибка http://joxi.ru/Y2L5leLsnoJEDA
http://joxi.ru/p27PZRei07gnoA
http://joxi.ru/5mdq1zptvOVay2
http://joxi.ru/zANWMeZcloz16r
Дебаг http://joxi.ru/eAOdEeaU4ojGGr
yii\web\Application->handleRequest(Object(yii\web\Request))
#14 D:\sites\yii2com\backend\web\index.php(17): yii\base\Application->run()
#15 {main}

ArticleSearch

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

<?php

namespace wokster\article\models;

use yii;
use yii\base\Model;
use yii\data\ActiveDataProvider;
use yiidreamteam\upload\FileUploadBehavior;
use wokster\article\models\ArticleSearch;

/* @var $this yii\web\View */
/* @var $searchModel \wokster\article\models\ArticleSearch*/
/* @var $dataProvider yii\data\ActiveDataProvider */

/**
 * ArticleSearch represents the model behind the search form about `common\models\Article`.
 */
class ArticleSearch extends Article
{
    public $fileUploud;

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['id', 'status_id', 'date_create', 'type_id'], 'integer'],
            [['title', 'url', 'text', 'image'], 'safe'],
            ['fileUpload', 'file'],
        ];
    }

    /**
     * @inheritdoc
     */
    public function scenarios()
    {
        // bypass scenarios() implementation in the parent class
        return Model::scenarios();
    }

    /**
     * Creates data provider instance with search query applied
     *
     * @param array $params
     *
     * @return ActiveDataProvider
     */
    public function search($params)
    {
        $query = Article::find();

        $dataProvider = new ActiveDataProvider([
            'query' => $query,
        ]);

        $this->load($params);

        if (!$this->validate()) {
            // uncomment the following line if you do not want to return any records when validation fails
            // $query->where('0=1');
            return $dataProvider;
        }

        $query->andFilterWhere([
            'id' => $this->id,
            'status_id' => $this->status_id,
            'date_create' => $this->date_create,
            'type_id' => $this->type_id,
        ]);

        $query->andFilterWhere(['like', 'title', $this->title])
            ->andFilterWhere(['like', 'url', $this->url])
            ->andFilterWhere(['like', 'text', $this->text])
            ->andFilterWhere(['like', 'image', $this->image]);

        return $dataProvider;
    }
}
Controller

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

<?php

namespace wokster\article\controllers;

use yii;
use wokster\article\models\Article;
use wokster\article\models\ArticleSearch;
use yii\web\MethodNotAllowedHttpException;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use yiidreamteam\upload\FileUploadBehavior;

/**
 * ArticleController implements the CRUD actions for Article model.
 */
class ArticleController extends yii\web\Controller
{
    public function behaviors()
    {
        return [
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['post'],
                ],
            ],
        ];
    }


    public function actions()
    {
        return [
           /* 'images-get' => [
                'class' => 'vova07\imperavi\actions\GetAction',
                'url' => \Yii::$app->controller->module->allRedactorImageUrl, // Directory URL address, where files are stored.
                'path' => \Yii::$app->controller->module->redactor_upload_path_alias, // Or absolute path to directory where files are stored.
                'type' => \vova07\imperavi\actions\GetAction::TYPE_IMAGES,
            ],*/
            'image-upload' => [
                'class' => 'vova07\imperavi\actions\UploadAction',
                'url' => \Yii::$app->controller->module->redactorImageUrl, // Directory URL address, where files are stored.
                'path' => \Yii::$app->controller->module->redactorPath, // Or absolute path to directory where files are stored.
            ],
        ];
    }

    /**
     * Lists all Article models.
     * @return mixed
     */
    public function actionIndex()
    {
        $searchModel = new ArticleSearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);

        return $this->render('index', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        ]);
    }

    /**
     * Displays a single Article model.
     * @param integer $id
     * @return mixed
     */
    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($type=null)
    {
        $model = new Article();
        if(is_numeric($type))
            $model->type_id = $type;

       /* if ($model->load(Yii::$app->request->post()) && $model->save()) {
            if(Yii::$app->request->post('toview',false)){
                return $this->redirect(['view', 'id' => $model->id]);
            }else{
                return $this->redirect(['update', 'id' => $model->id]);
            }*/
             if ($model->load(Yii::$app->request->post()) && $model->validate()) {
        // $file - атрибут в модели для хранения пути до файла (поле в таблице БД)
        $model->file = $model->getUploadedFileUrl('fileUpload');
        if($model->save())
            return $this->redirect(['view', 'id' => $model->id]);

        } else {
            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 integer $id
     * @return mixed
     */
    public function actionUpdate($id)
    {
        $model = $this->findModel($id);

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            return $this->redirect(['update', 'id' => $model->id]);
        } else {
            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 integer $id
     * @return mixed
     */
    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 integer $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;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }
}
Action.index

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

<?php

use \wokster\ltewidgets\BoxWidget;
use yii\widgets\Pjax;
use yii\grid\GridView;

/* @var $this yii\web\View */
/* @var $searchModel \wokster\article\models\ArticleSearch*/
/* @var $dataProvider yii\data\ActiveDataProvider */

$this->title = 'статьи';
$this->params['breadcrumbs'][] = $this->title;
?>

<?php // echo $this->render('_search', ['model' => $searchModel]); ?>
<?php BoxWidget::begin([
 'title'=>'статьи <small class="m-l-sm">записей '.$dataProvider->getCount().' из '.$dataProvider->getTotalCount().'</small>',
  'buttons' => [
      ['link', '<i class="fa fa-plus" aria-hidden="true"></i>',['create','type'=>$searchModel->type_id],['title'=>'создать статью']]
  ]
]);?>
<?php Pjax::begin(['id' => 'grid'])?>
<?= GridView::widget([
    'summary' => '',
    'dataProvider' => $dataProvider,
    'options' => ['class'=>'table-responsive minHeight'],
    'filterModel' => $searchModel,
    'columns' => [
        ['class' => 'yii\grid\SerialColumn'],
        ['class' => 'yii\grid\ActionColumn'],
        'id',
        'title',
        ['attribute'=>'url','format'=>'url', 'value'=>function($model){ return Yii::$app->frontUrlManager->createUrl(['/article/one','url'=>$model->url]);}],
        ['attribute' => 'status_id','label' => 'статус','filter'=> Yii::$app->modules['article']->status_list, 'value' => 'status'],
        ['attribute' => 'image', 'value' => 'smallImage', 'format'=>'image'],
        'date_create:datetime',
       ['attribute' => 'type_id','label' => 'тип','filter'=> $searchModel->getTypeList(),'value' => 'typeName'],

    ],
]); ?>
<?php Pjax::end();?>
<?php BoxWidget::end();?>
Аватара пользователя
Dominus
Сообщения: 892
Зарегистрирован: 2013.03.14, 21:27
Откуда: Россия, Иваново
Контактная информация:

Re: Не загружаются картинки.

Сообщение Dominus »

В модели

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

public $fileUploud;
заменить на

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

public $fileUpload;
Не спорь с дураком, иначе окружающие не правильно поймут кто из вас дурак!
Nex-Otaku
Сообщения: 831
Зарегистрирован: 2016.07.09, 21:07

Re: Не загружаются картинки.

Сообщение Nex-Otaku »

Вот это внимательность! O_o
Sandro
Сообщения: 10
Зарегистрирован: 2017.11.09, 15:03

Re: Не загружаются картинки.

Сообщение Sandro »

Да, действительно, эта опечатку долго бы искал..

Но исправив, возникли такие ошибки со status_id и Data Provaider, как это решить можно?
http://joxi.ru/ZrJMBeWT1o5naA

http://joxi.ru/VrwdyYaUKRGoWm
http://joxi.ru/5mdq1zptvOQqD2
http://joxi.ru/MAjqdzVtvg3YG2
Status 500 Route article/article/index
http://joxi.ru/5mdq1zptvOQJD2
#23 D:\sites\yii2com\vendor\yiisoft\yii2\base\Controller.php(157): yii\base\InlineAction->runWithParams(Array)
#24 D:\sites\yii2com\vendor\yiisoft\yii2\base\Module.php(528): yii\base\Controller->runAction('', Array)
#25 D:\sites\yii2com\vendor\yiisoft\yii2\web\Application.php(103): yii\base\Module->runAction('article', Array)
#26 D:\sites\yii2com\vendor\yiisoft\yii2\base\Application.php(386): yii\web\Application->handleRequest(Object(yii\web\Request))
#27 D:\sites\yii2com\backend\web\index.php(17): yii\base\Application->run()
#28 {main}
Аватара пользователя
Dominus
Сообщения: 892
Зарегистрирован: 2013.03.14, 21:27
Откуда: Россия, Иваново
Контактная информация:

Re: Не загружаются картинки.

Сообщение Dominus »

Заменить в Action.index

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

['attribute' => 'status_id','label' => 'статус','filter'=> Yii::$app->modules['article']->status_list, 'value' => 'status']
на

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

//...
[
    'attribute' => 'status_id',
    'label' => 'статус',
    'filter'=> Yii::$app->modules['article']->status_list,
    'value' => 'status_id',
    // или так
    /*'value' => function($data) {
        return $data->status_id;
    }*/
    // или вообще убрать этот параметр value
 ],
 //...
Не спорь с дураком, иначе окружающие не правильно поймут кто из вас дурак!
Sandro
Сообщения: 10
Зарегистрирован: 2017.11.09, 15:03

Re: Не загружаются картинки.

Сообщение Sandro »

Сейчас что-то с картинками в Article.index:
http://joxi.ru/Drl0KzPT48zEZr
http://joxi.ru/Dr8Ma3eTk6LEam
http://joxi.ru/a2XXlWytyok532
#24 D:\sites\yii2com\vendor\yiisoft\yii2\base\Module.php(528): yii\base\Controller->runAction('', Array)
#25 D:\sites\yii2com\vendor\yiisoft\yii2\web\Application.php(103): yii\base\Module->runAction('article', Array)
#26 D:\sites\yii2com\vendor\yiisoft\yii2\base\Application.php(386): yii\web\Application->handleRequest(Object(yii\web\Request))
#27 D:\sites\yii2com\backend\web\index.php(17): yii\base\Application->run()
#28 {main}
Последний раз редактировалось Sandro 2017.12.15, 19:45, всего редактировалось 2 раза.
Аватара пользователя
Dominus
Сообщения: 892
Зарегистрирован: 2013.03.14, 21:27
Откуда: Россия, Иваново
Контактная информация:

Re: Не загружаются картинки.

Сообщение Dominus »

Не определён в модели Article параметр smallImage
http://joxi.ru/Drl0KzPT48zEZr
Не спорь с дураком, иначе окружающие не правильно поймут кто из вас дурак!
Sandro
Сообщения: 10
Зарегистрирован: 2017.11.09, 15:03

Re: Не загружаются картинки.

Сообщение Sandro »

С чем связана эта ошибка?
GET http://admin.yii2.com/article/article/update?id=1 a
http://joxi.ru/823oWLeS6bERM2
yii\web\Application->handleRequest(Object(yii\web\Request))
#16 D:\sites\yii2com\backend\web\index.php(17): yii\base\Application->run()
#17 {main}

Страницы в backend открываются нормально, но при попытке редактировать или просмотр статей выходит такая ошибка:
Unknown Method – yii\base\UnknownMethodException
Calling unknown method: wokster\article\models\Article::getImage()
Последний раз редактировалось Sandro 2017.12.19, 21:42, всего редактировалось 1 раз.
Ответить