Метод POST передает не все данные

Общие вопросы по использованию второй версии фреймворка. Если не знаете как что-то сделать и это про Yii 2, вам сюда.
Ответить
sdema76
Сообщения: 1
Зарегистрирован: 2022.08.12, 11:53

Метод POST передает не все данные

Сообщение sdema76 »

Добрый день! Помогите, пожалуйста разобраться в чем проблема.
На сайте есть комментарии к товарам (просто текст), необходимо добавить возможность загрузить картинку.
Вот часть кода, который отвечает за комментарий на странице товара:

<div class="comment_form_block">
<script>
function formSend(form,data,hasError)
{
if(!hasError)
{
$.ajax(
{
type: "POST",
url: '<?= CHtml::normalizeUrl(array("comments/create"))?>',
data: form.serialize(),
success: function(data)
{
$(".comment_form_block").html(data);
},
});
}
}
</script>

<?php $form=$this->beginWidget('CActiveForm', array(
'id'=>'comments',
'enableAjaxValidation'=>false,
'enableClientValidation'=>true,
'clientOptions'=>array('validateOnSubmit'=>true, 'validateOnType'=>false, 'validateOnChange'=>false, 'afterValidate'=>'js:formSend'),
'htmlOptions'=>array('enctype'=>'multipart/form-data', 'style'=>'width:100%'),
)); ?>
<h2 id="review-title">Написать отзыв</h2>
<b><?php echo $form->labelEx($comment,'name'); ?></b><br>
<?php echo $form->textField($comment,'name',array('size'=>50,'maxlength'=>255)); ?>
<?php echo $form->error($comment,'name'); ?>
<br><br>
<b><?php echo $form->labelEx($comment,'comment'); ?></b><br>
<?php echo $form->textArea($comment,'comment',array('rows'=>5, 'cols'=>47)); ?>
<?php echo $form->error($comment,'comment'); ?>
<br><br>
<b><?php echo $form->labelEx($comment,'img_comment'); ?></b><br>
<?php echo $form->fileField($comment,'img_comment', array('class'=>'form_file')); ?>
<?php echo $form->error($comment,'img_comment'); ?>
<br><br>
<input type="hidden" id="Comments_id_product" name="Comments[id_product]" value="<?= $product->id ?>">
<div class="page-button">
<?php echo CHtml::SubmitButton('Отправить',array('class'=>'page-link2qwe', 'style'=>'background: none repeat scroll 0 0 rgba(0, 0, 0, 0);border: medium none;display: inline-block;padding-top: 11px;height: 40px;padding-top: 5px;width: 140px; cursor:pointer;')); ?>
</div>
<?php $this->endWidget(); ?>
</div>

Беда в том, что метод POST передает только текстовые данные (новые поля добавляла для теста - все работает), а поле файл (img_comment) - нет.
Когда загружается контроллер (CommentsController.php), то переменная $_POST такая: Array ( [Comments] => Array ( [name] => Светлана [comment] => Тестовый отзыв [img_comment] => [id_product] => 381 ) )
А переменная $_FILES пустая: Array ( ).

Я не сильна JavaScript, но кажется, что загвоздка в нем. Помогите пожалуйста понять в чем дело.


Ниже код класса Comments:
class Comments extends CActiveRecord
{
public static function model($className=__CLASS__)
{
return parent::model($className);
}

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

public function rules()
{
return array(
array('name, comment', 'required'),
array('id_product, active', 'numerical', 'integerOnly'=>true),
array('name, date', 'length', 'max'=>255),
array('img_comment', 'file', 'allowEmpty'=>true),
array('id, date, name, comment, id_product, img_comment, active', 'safe', 'on'=>'search'),
);
}

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(
);
}

public function attributeLabels()
{
return array(
'id' => 'ID',
'date' => 'Дата',
'name' => 'Ваше имя',
'comment' => 'Ваш отзыв',
'id_product' => 'Id товара',
'active' => 'Активность',
'img_comment' => 'Фото',
);
}

public function search()
{
// Warning: Please modify the following code to remove attributes that
// should not be searched.

$criteria=new CDbCriteria;

$criteria->compare('id',$this->id);
$criteria->compare('date',$this->date,true);
$criteria->compare('name',$this->name,true);
$criteria->compare('comment',$this->comment,true);
$criteria->compare('id_product',$this->id_product);
$criteria->compare('active',$this->active);
$criteria->compare('img_comment',$this->img_comment,true);

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

protected function beforeSave(){
if(!parent::beforeSave())
return false;

if($this->isNewRecord)
{
$this->date = date("c");
}

return true;
}
}
Аватара пользователя
SiZE
Сообщения: 2813
Зарегистрирован: 2011.09.21, 12:39
Откуда: Perm
Контактная информация:

Re: Метод POST передает не все данные

Сообщение SiZE »

обернитекодпожалуйстаоченьнеудобночитатьего
Ответить