Minggu, 18 Maret 2018

Upload file di yiiframework

Bikin fungsi upload file di yiiframework sebenernya gak susah-susah amat. cuma sering kali lupa nambahin 'htmlOptions'=>array('enctype'=>'multipart/form-data'), di form widget, alhasil form dah ngirim, file gak naik ke server.
Catatan berikut buat gampang kalau lupa lagi.



di view awalnya kalau generate pake gii isinya kurang lebih gini :

<?php 
$form=$this->beginWidget('CActiveForm', array(
'id'=>'content-form',
'enableAjaxValidation'=>false,
)); 
?>
<div class="row">
<div class="col">
       <?php echo $form->labelEx($model,'avatar'); ?>
       <?php echo $form->textField($model,'avatar'); ?>
       <?php echo $form->error($model,'avatar'); ?>
</div>
</div>

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

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

ubah $form->textField($model,'avatar') jadi $form-> fileField($model,'avatar')

tambah baris 'htmlOptions'=>array('enctype'=>'multipart/form-data'), dalam widget form

setelah dibenerin file view kurang lebih jadi gini :

<?php 
$form=$this->beginWidget('CActiveForm', array(
'id'=>'content-form',
'enableAjaxValidation'=>false,
'htmlOptions'=>array('enctype'=>'multipart/form-data'), 
)); 
?>
<div class="row">
<div class="col">
        <?php echo "Avatar <b>(.jpg)</b>"; ?>
           <?php echo $form->fileField($model,'avatar',
                 array(
                'size'=>20,
                'maxlength'=>200
           )); ?> 
        <?php echo $form->error($model,'avatar'); ?>
</div>
</div>

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

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




Tidak ada komentar: