@Maila

Как правильно установить загрузчик фото?

Пробую установить 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 Article.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');
    }
  });
");
  • Вопрос задан
  • 551 просмотр
Пригласить эксперта
Ответы на вопрос 1
@Arik
Везде юзаете file, а в поведение подключаете как image
'attribute' => 'image',
Ответ написан
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Похожие вопросы