Yii

A0
На сайте с 23.05.2015
Offline
0
569

Здравствуйте.

Делаю интернет магазин на YII 1.16. В нем к товарам можно загрузить изображение. Делается это так

Вот форма где пользователь вводит данные, в том числе изображения


<?php $form=$this->beginWidget('CActiveForm', array(
'id'=>'catalog-form',
// Please note: When you enable ajax validation, make sure the corresponding
// controller action is handling ajax validation correctly.
// There is a call to performAjaxValidation() commented in generated controller code.
// See class documentation of CActiveForm for details on this.
'enableAjaxValidation'=>false,
'method' => 'post',
'htmlOptions'=>array('enctype'=>'multipart/form-data'),
)); ?>

<p class="note">Поля со <span class="required">*</span> обязательны.</p>

<?php echo $form->errorSummary($model); ?>

<div class="row">
<?php echo $form->labelEx($model,'title'); ?>
<?php echo $form->textField($model,'title',array('size'=>60,'maxlength'=>255)); ?>
<?php echo $form->error($model,'title'); ?>
</div>

<div class="row">
<?php echo $form->labelEx($model,'image'); ?>
<?php echo $form->fileField($model, 'image'); ?>
<?php echo $form->error($model,'image'); ?>
<?php if(!$model->isNewRecord) {
echo CHtml::image(Yii::app()->baseUrl.'/images/catalog/thumb_small/' .$model->id . '_small.jpg');
}?>

</div>
// Остальные параметры.

Вот контроллер, который принимает эти изображения


public function actionCreate(){
$model=new Catalog;
if(isset($_POST['Catalog']))
{
$model->attributes=$_POST['Catalog'];
$model->image=CUploadedFile::getInstance($model,'image');
//Атрибуту icon присвоить указатель на загружаемый файл
if($model->save())
//Если надо сохранить модель
{
if ($model->image)
//Если пользователь загрузил файл
{
$file = 'images/catalog/'.$model->id. '_big.jpg';
//Переменной $file присвоить путь, куда сохранится картинка без изменений
$model->image->saveAs($file);
//Сохранить картинку без изменений по указанному пути
//Используем функции расширения CImageHandler ;
$ih = new CImageHandler(); //Инициализация
Yii::app()->ih
->load($file) //Загрузка оригинала картинки
->thumb('350', '350') //Создание превьюшки размером 200px
->save('images/catalog/thumb/'.
$model->id. '_small.jpg')
//Сохранение превьюшки в папку
->reload() //Снова загрузка оригинала картинки
->thumb('200', '200') //Создание превьюшки размером 50px
->save('images/catalog/thumb_small/'
.$model->id. '_small.jpg')
//Сохранение превьюшки в папку



//Сохранение превьюшки в папку
;
}
$this->redirect(array('index'));
}
}


$this->render('create',array(
'model'=>$model,
));
}

Изображения обрабатываются через CImageHandler

И вот модель


public function rules()
{
// NOTE: you should only define rules for those attributes that
// will receive user inputs.
return array(
array('title, image, text, price, status', 'required'),
array('created, price, status, price_opt, price_new, quantity_opt', 'numerical', 'integerOnly'=>true),
array('title, image', 'length', 'max'=>255),
array('image', 'file', 'types'=>'jpg, gif, png'),
// The following rule is used by search().
// @todo Please remove those attributes that should not be searched.
array('id, title, image, text, created, price, price_opt, price_new, quantity_opt, status', 'safe', 'on'=>'search'),
);
}

/**
* @return array relational rules.
*/
public function relations()
{
// NOTE: you may need to adjust the relation name and the related
// class name for the relations automatically generated below.
return array(
);
}

/**
* @return array customized attribute labels (name=>label)
*/
public function attributeLabels()
{
return array(
'id' => 'ID',
'title' => 'Название',
'image' => 'Фото',
'text' => 'Описание',
'created' => 'Создано',
'price' => 'Цена (рублей)',
'price_opt' => 'Цена опта (рублей)',
'price_new' => 'Новая цена (рублей)',
'quantity_opt' => 'Колличество опта',
'status' => 'Статус',

);
}

/**
* Retrieves a list of models based on the current search/filter conditions.
*
* Typical usecase:
* - Initialize the model fields with values from filter form.
* - Execute this method to get CActiveDataProvider instance which will filter
* models according to data in model fields.
* - Pass data provider to CGridView, CListView or any similar widget.
*
* @return CActiveDataProvider the data provider that can return the models
* based on the search/filter conditions.
*/
public function search()
{
// @todo Please modify the following code to remove attributes that should not be searched.

$criteria=new CDbCriteria;

$criteria->compare('id',$this->id);
$criteria->compare('title',$this->title,true);
$criteria->compare('image',$this->image,true);
$criteria->compare('text',$this->text,true);
$criteria->compare('created',$this->created);
$criteria->compare('price',$this->price);
$criteria->compare('price_opt',$this->price_opt);
$criteria->compare('price_new',$this->price_new);
$criteria->compare('quantity_opt',$this->quantity_opt);
$criteria->compare('status',$this->status);

return new CActiveDataProvider($this, array(
'criteria'=>$criteria,
'pagination'=>array(
'pageSize'=> 6,
),
));
}
public function beforeSave()
{

$this->created=time();
return parent::beforeSave();
}


/**
* Returns the static model of the specified AR class.
* Please note that you should have this exact method in all your CActiveRecord descendants!
* @param string $className active record class name.
* @return Catalog the static model class
*/
public static function model($className=__CLASS__)
{
return parent::model($className);
}
}

Все работает нормально, только хотелось бы загружать несколько изображений к товару. Как это лучше сделать?

TF-Studio
На сайте с 17.08.2010
Offline
334
#1

на форуме Yii ответ получить - шансы гораздо выше

Всё ещё лучший способ заработка для белых сайтов: GoGetLinks (https://www.gogetlinks.net/?inv=fahbn8).
Ragnarok
На сайте с 25.06.2010
Offline
239
#2

Artur07, с нуля пишете, или готовое решение?

//TODO: перестать откладывать на потом
A0
На сайте с 23.05.2015
Offline
0
#3

С нуля. Но решение по загрузке изображений нашел готовое (с использованием CImageHandler), просто хотел бы расширить функционал.

Авторизуйтесь или зарегистрируйтесь, чтобы оставить комментарий