CForm and load image

I need a form to load image on server. model


<?php

class Item extends CFormModel


{

    public $image;

    public $retro;

 

    public function rules()

    {

        return array(

            array('image', 'file', 'types'=>'jpg, gif, png, eps'),

        );

    }

}

?>

controller


<?php


class ItemController extends CController

{

    public function actionLoad()

    {

		$model=new Item;

        if(isset($_POST['image']))

        {

            $model->attributes=$_POST['image'];

            $model->image=CUploadedFile::getInstance($model,'image');

            if($model->save())

            {

                $model->image->saveAs('images/test');

            }

        }

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

    }

}


?>

and form


<?php echo CHtml::beginForm('','post',array('enctype'=>'multipart/form-data')); ?>

<?php echo CHtml::activeFileField($model, 'image'); ?>

<?php echo CHtml::activeTextField($model, 'retro'); ?>

<?php echo CHtml::submitButton('Create' ); ?>

<?php echo CHtml::endForm(); ?>

this code copied from cookbook and just a little modified but it doesn`t work. strange thing is if i var_dump($_post) value "image" always is empty. what wrong - why image empty?

i also had some problems with image loading and what i did is the following:




<?php echo CHtml::beginForm('','post',array('enctype'=>'multipart/form-data')); ?>

<?php echo CHtml::fileField('image'); // activeField here?>

<?php echo CHtml::activeTextField($model, 'retro'); ?>

<?php echo CHtml::submitButton('Create' ); ?>

<?php echo CHtml::endForm(); ?>




On the controller





$picture_file = CUploadedFile::getInstanceByName('image');


// here I check with a function all validation required with the file

// if you need help with this i will write the validation function 

// then i update the model attributes (you already know how to do that $model->image = 'blabla';

// and save

$picture_file->saveAs('images/test');




Like this I assure you that works, I do follow this in my projects. I was a bit tired that when creating was working and when updating not. I may have solved that issue by not using validation on update but I rather use this approach. This is why I love Yii… flexibility.

Great thanks, it is my fault:


if(isset($_POST['image'])) 

  • rigth

if(isset($_POST['Item'])) 

, model name is Item.

Congrats man!

Remember to mark your post title as [RESOLVED]