Загрузка изображения Yii не работает в действии Обновление

1

Я использую YII Framework, но когда я обновляю свою информацию, исключая изображение, он бросает ошибку, что тип изображения недействителен, даже у меня есть допустимый тип iamge. он выдает ошибку, которая исправит следующие ошибки ввода: Изображение не может быть пустым. Выберите правильный формат файла

public function actionUpdate($id) {
    $model = $this->loadModel($id);
    $oldImage = $model->image;
    if (isset($_POST['Product'])) {
        $model->attributes = $_POST['Product'];
        $rnd = rand(0, 9999);  // generate random number between 0-9999
        $uploadedFile = CUploadedFile::getInstance($model, 'image');
        if (!empty($uploadedFile)) {
            $fileName = "{$rnd}" . time() . "{$uploadedFile}";  // random number + file name
            $model->image = $fileName;
            $uploadedFile->saveAs(Yii::app()->basePath . '/../images/product/' . $fileName);
            @unlink(Yii::app()->basePath . "\\..\\images\\product\\" . $oldImage);
        } else {
            $model->image = $oldImage;
        }
        if ($model->save())
            $this->redirect(array('view', 'id' => $model->id));
    }
    $this->render('update', array(
        'model' => $model,
    ));
}

и мой файл _form ниже

<div class="form">

<?php
$form = $this->beginWidget('CActiveForm', array(
    'id' => 'product-form',
    'enableAjaxValidation' => false,
    'htmlOptions' => array('enctype' => 'multipart/form-data'),
));
?>
<p class="note">Fields with <span class="required">*</span> are required.</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' => 256)); ?>
    <?php echo $form->error($model, 'title'); ?>
</div>

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

<div class="row">
    <?php
    echo $form->labelEx($model, 'image');
    echo CHtml::activeFileField($model, 'image');
    echo $form->error($model, 'image');
    ?>
</div>

<?php if ($model->isNewRecord != '1') {
    ?>
    <div class="row">
        <?php echo CHtml::image(Yii::app()->request->baseUrl . '/images/product/' . $model->image, "image", array("width" => 200)); ?>
    </div>

<?php } ?>

<div class="row">
    <?php
    echo $form->labelEx($model, 'status');
    echo $form->dropDownList($model, 'status', array('active' => 'Active', 'inactive' => 'InActive'), array('empty' => 'Select Status'));
    echo $form->error($model, 'status');
    ?>
</div>


<div class="row buttons">
    <?php echo CHtml::submitButton($model->isNewRecord ? 'Create' : 'Save'); ?>
</div>

<?php $this->endWidget(); ?>

и моя модель ниже

<?php

class Product extends CActiveRecord {

public function tableName() {
    return 'products';
}

public function rules() {
    // NOTE: you should only define rules for those attributes that
    // will receive user inputs.
    return array(
        array('title, image, status', 'required'),
        array('image', 'file', 'types' => 'jpg, gif, png', 'message' => 'Please choose correct file format'),
        array('created_by, modified_by', 'numerical', 'integerOnly' => true),
        array('title', 'length', 'max' => 256),
        array('slug', 'length', 'max' => 256),
        array('status', 'length', 'max' => 8),
        array('image, created_at, modified_at', 'safe'),
        // The following rule is used by search().
        // @todo Please remove those attributes that should not be searched.
        array('id, title, slug, image, status, created_at, created_by, modified_at, modified_by', 'safe', 'on' => 'search'),
    );
}

/**
 * @return array relational rules.
 */
public function relations() {
    return array(
        'productitems' => array(self::HAS_MANY, 'Productitems', 'proid'),
    );
}

/**
 * @return array customized attribute labels (name=>label)
 */
public function attributeLabels() {
    return array(
        'id' => 'ID',
        'title' => 'Title',
        'slug' => 'Slug',
        'image' => 'Image',
        'status' => 'Status',
        'created_at' => 'Created At',
        'created_by' => 'Created By',
        'modified_at' => 'Modified At',
        'modified_by' => 'Modified By',
    );
}

/**
 * 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('slug', $this->slug, true);
    $criteria->compare('image', $this->image, true);
    $criteria->compare('status', $this->status, true);
    $criteria->compare('created_at', $this->created_at, true);
    $criteria->compare('created_by', $this->created_by);
    $criteria->compare('modified_at', $this->modified_at, true);
    $criteria->compare('modified_by', $this->modified_by);

    return new CActiveDataProvider($this, array(
        'criteria' => $criteria,
    ));
}

/**
 * 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 Product the static model class
 */
public static function model($className = __CLASS__) {
    return parent::model($className);
}

}

Теги:
file
yii

1 ответ

0

Вы используете CFileValidator для image поля в вашем классе Product, и вы ограничиваете форматы, которые могут быть загружены, поскольку они написаны в следующей строке:

array('image', 'file', 'types' => 'jpg, gif, png', 'message' => 'Please choose correct file format'),

Проблема, с которой вы сталкиваетесь, заключается в том, что CFileValidator не позволяет по умолчанию пустым портировать поля, поэтому вам необходимо явно установить для атрибута allowEmpty правила значение true.

При этом ваше правило должно быть написано следующим образом:

array('image', 'file', 'types' => 'jpg, gif, png', 'allowEmpty' => true, 'message' => 'Please choose correct file format'),

Вы можете узнать больше о валидации правил модели по следующей ссылке: http://www.yiiframework.com/wiki/56/#hh12

Надеюсь, поможет.

Ещё вопросы

Сообщество Overcoder
Наверх
Меню